如何实现子进程向文件f.txt中写入内容"Hello Process" 父进程负责子进程退出后从f.txt中读出内容并显示出来

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
   pid_t  pid;
   printf("before fork\n");
   pid = fork();
   if(pid < 0)
   {  
     perror("fork error");
   }
   else if(0 == pid)
   {  //child
        char ch[] = "Hello Process";
        int fd = -1;
        fd = open("f.txt",O_WRONLY);
          while(fd > 0)
        {
            write(fd,&ch,1);
        }
      close(fd);
   }
   else
   { //parent
          char ret[] = "Hello Process";
        int fd = -1;
        fd = open("f.txt",O_RDONLY);
        while(fd > 0)
        {
            read(fd,output,1);
        }
        close(fd);
   }
   printf("pid = %s\n",pid);
   return 0;
阅读 3.1k
1 个回答

使用父进程waitpid等待子进程退出

另外,把代码格式改改吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题