Linux 多进程编程实例(一)

目标:

一个进程,创建两个子进程,利用exec函数族使两个子进程执行不同的程序。子进程1执行ls -l命令后正常返回,子进程2暂停5s后异常返回,父进程阻塞方式等待进程1,非阻塞方式等待进程2,等父进程收集到进程2的返回信息后就退出。

main.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, const char *argv[])
{
    int i;
    pid_t pid1 = 0, pid2 = 0, pid = 0;
    int *status1, *status2;
    int k=0;

    for (i = 0; i < 2; i++) {
        if (0 == i) pid = pid1 = fork();
        else        pid = pid2 = fork();

        if (pid < 0) {
            perror("pid fork");
            exit(-1);
        } else if (pid == 0) {   //子进程
            break;
        } else {   //父进程处理
            waitpid(pid1, status1, 0);         //阻塞方式等待
            
            do {                               //非阻塞方式等待
                k = waitpid(pid2, status2, WNOHANG);  
                if (k == 0) {
                    printf("process2 still runing\n");
                    sleep(1);
                } 
            }while (k == 0);

        }

    }

    /************ 子进程处理 *******************/
   
    if (0 == i) {      // 进程1 
        if (-1 == execl("./process1", NULL)) {
            perror("process1 exec");
            exit(-1);
        }
    } else if (1 == i) {   // 进程2  切记这里要i == 1,因为上面结束后没有判断i==1的话回执行两次,相当于在process2中又调用了process2
        if (-1 == execl("./process2", NULL)) {
            perror("process2 exec");
            exit(-1);
        }
    }

    printf("parent process exit!!!\n"); //父进程结束
    exit(0);
}

process1.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


int main(int argc, const char *argv[])
{
    if (-1 == execlp("ls", "ls", "-l", NULL)) {
            perror("process1");
            exit(-1);
        }
    exit(0);
}

process2.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


int main(int argc, const char *argv[])
{
    // int i;
    // for (i = 1; i < 6; i++) {
    //     sleep(1);
    //     printf("%ds\n", i);
    // }

    sleep(5);
    exit(-1);
}

程序运行结果如下:

在这里插入图片描述

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值