打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
多进程编程小例子(YC)
多进程编程例子1:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
    pid_t pid;
    //pid = fork();
    if((pid=fork())==-1) {
      printf("fork error\n");
      return -1;
    }

    else if(pid==0) {
    while(1) {
      printf("In the child process\n"); sleep(1); }
    }

    else {
    while(1) {
     printf("In the parent process\n"); sleep(1); }
    }

    return 0;
}

多进程编程例子2:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    pid_t pid;
    int i=1;
    int fd;
    int status;
    char *t1="hello";
    char *t2="test";
    char *t3="now\n";
    
    fd=open("test.txt",O_RDWR | O_CREAT, 0644);
    if(fd<0) {
    perror("parent open error\n");
    exit(EXIT_FAILURE);
    }

    if((write(fd,t1,strlen(t1)))<0) {
    perror("parent write error\n");
    exit(EXIT_FAILURE);
    }
    
    printf("current pid=%d\n",getpid());

    pid = fork();
    if(pid<0) {
    perror("fork error\n");
    exit(EXIT_FAILURE);
    }

    else if(pid==0) {
    i=2;
    if((write(fd,t2,strlen(t2)))<0) perror("child write error\n");
    printf("in child i=%d,cid=%d,pcid=%d\n",i,getpid(),getppid());
    return 0;
    }

    else {
    sleep(1);
    if((write(fd,t3,strlen(t3)))<0) perror("parent write error\n");
    printf("in parent i=%d,pid=%d\n",i,getpid());
    wait(&status);
    return 0;
    }
}
运行结果:
test.txt内容:hellotestnow


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Linux系统编程之我的学习笔记1_linux函数学习心得
孤儿进程与僵尸进程[总结]
linux 进程(二)
socketpair理解
linux程序设计
linux管道通信
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服