fork调用

来源:互联网 发布:淘宝商品优惠券 编辑:程序博客网 时间:2024/06/03 18:09

#include <sys/types.h>#include <sys/stat.h>#include <sys/uio.h>#include <unistd.h>#include <fcntl.h>#include <string.h>#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>int main(){    char buf[100] = {0};    pid_t child_pid;    int fd = 0;    int status = 0;    if ((fd = open("temp", O_CREAT|O_RDWR|O_TRUNC, 0664)) == -1)    {        perror("创建文件");        exit(1);    }    strcpy(buf, "父进程数据");    if ((child_pid = fork()) == 0)    {        printf("fork() return value in children process : %d\n", child_pid);        strcpy(buf, "子进程数据");        puts("child process is running!");        printf("child process pid = %d\n", getpid());        printf("father process pid = %d\n", getpid());        int write_bytes = write(fd, buf, strlen(buf));        close(fd);        exit(0);    }    else    {        printf("fork() return value in parent process : %d\n", child_pid);        puts("father process is running!");        printf("father process pid = %d\n", getpid());        printf("child process pid = %d\n", getpid());        int write_bytes = write(fd, buf, strlen(buf));        close(fd);    }    wait(&status);    return 0;}



fork() return value in parent process : 2948

father process is running!

father process pid = 2947
child process pid = 2947
fork() return value in children process : 0
child process is running!
child process pid = 2948

father process pid = 2948


fork系统调用有两个函数,分别是fork和vfork,fork系统调用可以创建一个子进程

pid_t fork(void);

pid_t vfork(void);

pid_t是用来保存进程PID信息的结构体,当调用执行成功时,该调用对父进程返回子进程的PID,对子进程返回0。若调用失败,返回-1,子进程不创建,vfork函数形式相同,区别是vfork函数创建子进程时,不复制父进程的上下文。


从上面代码段的执行结果来看,父进程调用子进程后,父进程由内核状态转为用户转改,子进程开始执行并输出了消息,然后子进程调用exit函数进入僵死状态,父进程由用户状态重新回到内核状态,并输出信息,最后父进程等待子进程结束,父进程结束


子进程是从fork调用出开始执行的,因此fork不会被执行两次,代码中的fork返回给父进程和子进程的值不同,因此可以作为区分父进程和子进程的区别

原创粉丝点击