全部,我正在运行下面的程序并在问题结束时收到输出。我不确定这是否是我对execl的理解上的差距,或者我在这里完全错误地做了什么。代码很简单,参数/输出如下所示:
编辑:修正sizeof(arg)以反映arg的实际大小;但是,你可以看到它返回一个令人费解的'1',尽管它的大小应该是2。
int shell (int argc, char *argv[]) {
char *s; /* user input string */
tok_t *t; /* tokens parsed from input */
int lineNum = 0;
int fundex = -1;
pid_t pid = getpid(); /* get current processes PID */
pid_t ppid = getppid(); /* get parents PID */
printf("%s running as PID %d under %d\n",argv[0],pid,ppid);
lineNum=0;
fprintf(stdout,"%d: ",lineNum);
while ((s = freadln(stdin))) {
t = getToks(s); /* Break the line into tokens */
fundex = lookup(t[0]); /* Is first token a shell literal */
if (fundex >= 0) cmd_table[fundex].fun(&t[1]);
else { /* Treat it as a file to exec */
cmd_fork(t);
}
fprintf(stdout,"%d: ",++lineNum);
}
return 0;
}
int cmd_fork(tok_t arg[]) {
size_t size = 120;
int i, status = 0;
pid_t childPid;
char *nargs = (char *) malloc(size);
printf("sizeof arg: %lu\n", (sizeof(arg)/sizeof(tok_t))); // returns 1?
if ((sizeof(arg)/sizeof(tok_t)) >= 2) {
printf("arg0: %s, arg1: %s\n", arg[0], arg[1]);
if (sizeof(arg) > 2) {
for (i=1; i < sizeof(arg); i++) {
if (i > 1) {
strcat(nargs, " ");
}
strcat(nargs, arg[i]);
printf("Nargs: %s\n", nargs);
}
}
execl(arg[0], arg[0], nargs, NULL);
_exit(127);
}
if (childPid > 0) {
waitpid(childPid, &status, 0);
printf("Exit status of process was %d\n", status);
} else {
printf("Child failed");
}
return 0;
}
输出:
./shell running as PID 3595 under 1833
0: /usr/bin/wc /home/vagrant/example
T0: /usr/bin/wc, T1: /home/vagrant/example
arg0: /usr/bin/wc, arg1: /home/vagrant/example
sizeof arg: 1
/usr/bin/wc: invalid zero-length file name
Exit status of process was 256
我不太确定会出现什么问题,但我真的很欣赏任何指向正确的方向。
谢谢,
沫
答案 0 :(得分:0)
正如@ 5gon12eder所指出的那样,我的身材很大,因此圈塞了。最终解决方案如下所示。很遗憾因为我没有及早查看属于parse.c
的{{1}}。
parse.h