[英]Executing a program using fork and exec
I am new to C programming. 我是C编程的新手。 I am trying to run a program given by the path specified by the user using the
fork()
, exec()
, and waitpid()
commands. 我试图使用
fork()
, exec()
和waitpid()
命令运行由用户指定的路径给出的程序。 I have been trying to get this to run correctly for hours now and I keep getting errors I am not sure how to troubleshoot, as soon as I solve one error, new ones arise. 我一直试图让它正常运行几个小时,我不断收到错误我不知道如何解决问题,一旦我解决了一个错误,就会出现新问题。 I was wondering if someone can help me understand why my implementation does not work smoothly?
我想知道是否有人可以帮助我理解为什么我的实施不能顺利进行?
Many thanks 非常感谢
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char command1[256], command2[256], path[556];
printf("# ");
scanf("%s", command1);
scanf("%s", command2);
scanf("%s", path);
if(strcmp(command1,"quit")==0)
exit(0);
else if(strcmp(command1, "run")==0 && strcmp(command2, "command")==0){
printf("%s", path);
pid_t process;
process = fork();
//fork error
if (process < 0){
perror("fork");
exit(0);
}
else if (process > 0){ //this is the parent process
execl(path, "sh" , "-c", ":ls -l *.c", 0);
}
else {//this is the child process
waitpid(process); //waits until the program terminates
}
}
return 0;
}
It looks to me like you have things swapped. 它看起来像你有交换的东西。 With fork/exec, you generally do the exec in the child process, and the waitpid in the parent process.
使用fork / exec,您通常在子进程中执行exec,在父进程中执行waitpid。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.