简体   繁体   中英

Third process “wc” won't work

I'm currently having a problem with the third process because it wont work every time when I run the program. And suggestions with the exit() part because is printing multiple child process! Any suggestions?

I would really APPRECIATE it a lot!

main(){
    pid_t son;
    int i;  
    for (i=0; i<3; i++){
        switch (i){
            case 0:
            son = fork();
                if (son<0){
                    fprintf(stderr, "Fork failed!");
                    //exit(-1);
                }else if (son == 0){
                    execlp("/bin/cat", "cat", "wctrial.txt", NULL);
                }else{
                wait(NULL);
                printf("Child process completed!");
                //exit(0);
                }
            case 1:
            son = fork();
                if (son<0){
                    fprintf(stderr, "Fork failed!");
                    //exit(-1);
                }else if (son == 0){
                    execlp("/bin/mkdir", "mkdir", "mydirectory", NULL);
                }else{
                wait(NULL);
                printf("Child process completed!");
                //exit(0);
                }
            case 2:
            son = fork();
                if (son<0){
                    fprintf(stderr, "Fork failed!");
                    //exit(-1);
                }else if (son == 0){
                    execlp("/bin/wc","wc","wctrial.txt", NULL);
                }else{
                wait(NULL);
                printf("Child process completed!");
                //exit(0);
         }
    }
}

At least I don't see the break at the end of the each case .

In the case of 0 the program will run through all of your case s.

Actually break is the problem that if case 1 execute then 2,3 also will.( but this is not problem that wc not working )

Why wc is not working ?

Because of path of wc command!

In your system path for wc may not is: "/bin/wc"

Search tha path of wc command in your system like:

:~$ whereis wc
wc: /usr/bin/wc   

and change

 execlp("/bin/wc","wc","wctrial.txt", NULL);
           ^ 

as

 execlp("/usr/bin/wc","wc","wctrial.txt", NULL);
          ^ 
          // actually not exactly this but one that appears in your system. 

Give it a try!!

Below are my suggestion ,

1st) suggestion would be the clean-up of child process once it is done, as below,

 }else if (son == 0){
        execlp("/bin/mkdir", "mkdir", "mydirectory", NULL);
        _exit(0);
 }

2nd) do break after each switch statement

3rd) and also validate the path of executable by using "whereis" command before feeding into execlp routine.

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