多个execlp无法正常工作 [英] Multiple execlp not working
问题描述
在这里我需要一些帮助.运行程序后,我需要执行所有三个execlp(),但是发生的是只有case 0被执行,我将pid更改为1,而case1被执行了,依此类推.尝试将其置于for循环中,但不起作用.我将中断更改为继续,但仍然相同-仅执行一个进程.有什么建议吗?
I need some help here. I need to execute all three execlp() once I run the program but what happen is that only case 0 is executed.I changed pid to 1 and case1 gets executed and so on. Tried putting it in a for loop but does not work. I changed break to continue but still the same - only one process is executed. Any suggestions?
main(){
pid_t pid;
pid= fork();
int i;
if(pid==0){
for (i=0; i<3; i++){
switch (i){
case 0:
execlp("/bin/cat", "cat", "wctrial.txt", NULL);
break;
case 1:
execlp("/bin/mkdir", "mkdir", "mydirectory", NULL);
break;
case 2:
execlp("/bin/wc", "wctrial.txt", NULL);
break;
}
}
}else{
wait(NULL);
printf("Child process completed!");
exit(0);
}
}
推荐答案
根据 man execlp
:
exec()
系列功能用新的过程图像替换当前过程图像.
The
exec()
family of functions replaces the current process image with a new process image.
(强调是我的)
因此,一旦成功调用execlp
,该过程就不会重新执行旧代码.
Therefore, once you called successfully execlp
, the process doesn't re-execute the old code.
case 0:
execlp("/bin/cat", "cat", "wctrial.txt", NULL);
/* shouldn't go here */
break;
如果要执行这三个程序,则可以创建三个进程.例如(展开的循环):
If you want to execute the three programs, you can create three processes. For instance (loops unrolled):
pid_t son;
son = fork();
if (son == -1) /* report */
else if (son == 0) execlp("/bin/cat", "cat", "wctrial.txt", NULL);
else wait(NULL);
son = fork();
if (son == -1) /* report */
else if (son == 0) execlp("/bin/mkdir", "mkdir", "mydirectory", NULL);
else wait(NULL);
/* ... */
这篇关于多个execlp无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!