C小程序 - fork,在子进程中重定向输出,然后执行shell程序

2607阅读 0评论2012-10-29 niannian
分类:C/C++

fork,在子进程中重定向输出,然后执行shell程序

  1. if( (pid = fork() ) == -1 ){
  2.         perror("fork"); exit(1);
  3.     }
  4.     /* child does the work */
  5.     if ( pid == 0 ){
  6.         /* close then open */
  7.         close(1);
  8.         if ( open(file,O_WRONLY|O_CREAT|O_APPEND,DFLMODE) != 1 )
  9.             perror(file);
  10.         else {
  11.             execlp( "who", "who", NULL );    /* and run    */
  12.             perror("execlp");
  13.         }
  14.         exit(1);
  15.     }
  16.     /* parent waits then reports */
  17.     if ( pid != 0 ){
  18.         wait(NULL);
  19.         printf("Done running who. results in %s\n", file);
  20.     }


上一篇:C小程序 - 将stdin定向到文件
下一篇:C小程序 - fork,在子进程中重定向输入,然后执行shell程序