c - execve grep process never exit -


the following code simulate pipe , grep operation forking process , using execve system call. output seems fine, however, grep process seems never exit (still running in back) until whole process ends. what's problem? abnormal since using grep in shell exit.

#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> #include <fcntl.h> int main(int argc, char *argv[], char *env[]) { char ch[32]; while (1) {     scanf("%s", ch);     int pd[2];     if (pipe(pd) == -1) {         perror("pipe failed");         exit(1);     }      int childpid, pid;     if ((childpid = fork()) < 0) {         perror("fork failed\n");         exit(1);     } else {         // parent process         if (childpid) {             int status;             wait(&status);             // print exit code of child process             printf("exit code %d\n", status);         }         // child process, execute command         else {             // fork child             if ((pid = fork()) < 0) {                 perror("fork failed\n");                 exit(1);             }             if (pid) {   // parent pipe writer                 close(pd[0]);                 close(1);                 // replace input pipe                 dup(pd[1]);                 char* cmds[] = { "/bin/cat", "aa", 0 };                 execve(cmds[0], cmds, env);                  exit(0);             } else {   // child pipe reader                 close(pd[1]);                 close(0); // close read end                 dup(pd[0]);                  char* cmds[] = { "/bin/grep", "rw", 0 };                 execve(cmds[0], cmds, env);                 exit(0); // never been here             }         }     } } return 0; } 

here output monitor process before , after running program once.

hengstar@ubuntu:~$ ps -ef | grep "grep" hengstar 58073 58038  0 01:43 pts/26   00:00:00 grep --color=auto grep hengstar@ubuntu:~$ ps -ef | grep "grep" hengstar 58075  1886  0 01:43 pts/11   00:00:00 /bin/grep drw hengstar 58077 58038  0 01:43 pts/26   00:00:00 grep --color=auto grep 

the exec family of functions never returns. purpose load new program replace current program running in process.

if exec function returns, means there error.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

python - RuntimeWarning: PyOS_InputHook is not available for interactive use of PyGTK -