简体   繁体   English

多个execlp无法正常工作

[英]Multiple execlp not working

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. 运行程序后,我需要执行所有三个execlp(),但是发生的是只执行case 0,我将pid更改为1,而case1得到执行,依此类推。 Tried putting it in a for loop but does not work. 尝试将其放入for循环中,但不起作用。 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);
}

} }

According to man execlp : man execlp

The exec() family of functions replaces the current process image with a new process image. exec()系列函数当前过程映像替换为新的过程映像。

(emphasis is mine) (重点是我的)

Therefore, once you called successfully execlp , the process doesn't re-execute the old code. 因此,一旦成功调用execlp ,该过程就不会重新执行旧代码。

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);

/* ... */

See also Kirilenko's answer. 另请参见基里连科的答案。 The solution is to use system(..) instead of execlp(..) . 解决方案是使用system(..)而不是execlp(..)

Man page here . 手册页在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM