作为我的代码的一部分,我正在尝试编写一个函数,以便用户可以键入
shell> run date //Line of user input
Mon Jan 19 11:51:57 EST 2009 //Printed by program
shell: process 348 exited normally with status 0
用户只需键入“运行日期”,程序就会显示底部的两行。 到目前为止,这是我在我的职能中所拥有的..
else if(strcmp(argv[1],"run") == 0 ) {
if ((pid = fork()) < 0) { //Child process fork
perror("fork");
exit(1);
}
//printf("ok");
if (pid == 0) { //Child executes code
execvp(argv[2], &argv[2]);
exit(1);
}
waitpid(atoi(argv[2]), &status, WNOHANG);
printf("shell: run status is %d\n", status);
}
这还没有产生,但我想知道到目前为止这是否正确以及我是否遗漏了重要的部分!谢谢。
最佳答案
waitpid
的第一个参数应该是 child 的 PID。另外,请注意 WNOHANG 选项可防止调用进程被阻塞;因此,如果预期进程的状态信息不可用,waitpid
将返回 0。如果您想等到 child 终止,请使用 0
作为 waitpid
的第三个参数(或使用 wait
而不是 waitpid
)。
关于C: 'run' 命令使用 waitpid & 命令行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896536/