ʵ

来自「清华大学出版社<linux c编程>的配套代码」· 代码 · 共 41 行

TXT
41
字号
#include <sys/types.h>
#include <unistd.h> 
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
extern int errno;
int main()
{
  char buf[100];
  pid_t cld_pid;
  int fd;
  int status;
if ((fd=open("temp",O_CREAT|O_TRUNC | O_RDWR,S_IRWXU)) == -1)
  {
   printf("open error %d",errno);
   exit(1);
   }
  strcpy(buf,"This is parent process write");
  if ((cld_pid=fork()) == 0)
    { /* 这里是子进程执行的代码 */
         strcpy(buf,"This is child process write");
         printf("This is child process");
         printf("My PID(child) is %d",getpid()); /*打印出本进程的ID*/
         printf("My parent PID is %d",getppid()); /*打印出父进程的ID*/
         write(fd,buf,strlen(buf));
         close(fd);
         exit(0);
     }
    else
         { /* 这里是父进程执行的代码 */
       printf("This is parent process");
       printf("My PID(parent) is %d",getpid()); /*打印出本进程的ID */
       printf("My child PID is %d",cld_pid); /*打印出子进程的ID*/
       write(fd,buf,strlen(buf));
       close(fd);
        }
    wait(&status);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?