考虑以下几点:
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
char *input_arg[2];
char *input_str = NULL;
size_t input_len = 0;
char **args;
ssize_t len;
size_t n;
pid_t child, p;
int status;
if (argc < 2) {
/* No command line parameters. Read command from stdin. */
len = getline(&input_str, &input_len, stdin);
/* Find length excluding the newline at end. */
if (len > (ssize_t)0)
n = strcspn(input_str, "\r\n");
else
n = 0;
if (n > (size_t)0) {
/* Terminate input command before the newline. */
input_str[n] = '\0';
} else {
fprintf(stderr, "No input, no command.\n");
return 1;
}
input_arg[0] = input_str;
input_arg[1] = NULL;
args = input_arg;
} else {
/* Use command line parameters */
argv[argc] = NULL;
args = argv + 1;
}
child = fork();
if (child == (pid_t)-1) {
fprintf(stderr, "Cannot fork: %s.\n", strerror(errno));
return 1;
}
if (!child) {
/* This is the child process. */
errno = ENOENT;
execvp(args[0], args);
fprintf(stderr, "%s: %s.\n", args[0], strerror(errno));
exit(127);
}
do {
p = waitpid(child, &status, 0);
} while (p == (pid_t)-1 && errno == EINTR);
if (p == (pid_t)-1) {
fprintf(stderr, "Lost child process: %s.\n", strerror(errno));
return 127;
}
if (p != child) {
fprintf(stderr, "waitpid() library bug occurred.\n");
return 127;
}
if (WIFEXITED(status)) {
if (!WEXITSTATUS(status))
fprintf(stderr, "Command successful.\n");
else
fprintf(stderr, "Command failed with exit status %d.\n", WEXITSTATUS(status));
return WEXITSTATUS(status);
}
if (WIFSIGNALED(status)) {
fprintf(stderr, "Command died by signal %s.\n", strsignal(WTERMSIG(status)));
return 126;
}
fprintf(stderr, "Command died from unknown causes.\n");
return 125;
}
上述用途如果指定的命令行参数,否则它读取一个从标准输入。由于标准输入不是标记化的,因此只能提供命令名称,不能提供参数。如果放大input_arg[]
数组
char *input_arg[4];
,并修改分配到
input_arg[0] = "/bin/sh";
input_arg[1] = "-c";
input_arg[2] = input_str;
input_arg[3] = NULL;
args = input_arg;
然后输入字符串将使用/bin/sh
外壳进行处理,就像popen()
一样。
您也可以使用len = getdelim(&input_str, &input_len, '\0', stdin);
并删除input_str[n] = '\0';
赋值以允许多行输入;只要shell足够短以适应命令行参数缓冲区(最大长度取决于您的操作系统),那么shell应该处理的很好。
shell将输入分割为单独的命令和参数的规则相当复杂,你不应该试图模拟它们。相反,找到一个简单的方法让用户分别指定参数(如命令行参数大小写),或使用shell为您执行。如果你没有做任何拆分,你可能需要删除输入行末尾的换行符。
的一点要注意的是,对于execvp(file, args)
,args[0]
是应用程序看到的名称(如$0
或argv[0]
)和args[1]
是第一参数。每个参数都由NUL(\0
)终止,就像字符串通常在C中一样,args
指针数组必须以NULL
指针结束。如果没有参数,则args[1] == NULL
。
它为什么不起作用。它做什么,你没有预料到? – slugonamission
'read'是一个未初始化的指针。你在期待什么? –
我想你想从文本文件中逐行读取命令行并执行它? –