简体   繁体   中英

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

}

According to man execlp :

The exec() family of functions replaces the current process image with a new process image.

(emphasis is mine)

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

/* ... */

See also Kirilenko's answer. The solution is to use system(..) instead of execlp(..) .

Man page here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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