进程的创建和控制

本文通过示例代码介绍了Linux下如何使用fork()、wait()、exec()等函数创建、控制进程,并展示了如何获取和输出进程信息。通过vfork()函数创建新进程,并在子进程中使用exec()调用不同命令或自定义可执行文件。
摘要由CSDN通过智能技术生成

1. /* example12-1.c     使用fork()函数创建1个新进程.*/

 

#include <stdlib.h>

#include <stdio.h>

#include <unistd.h>

int main( )

{

  pid_t  pid;

  pid = fork();                                          /* 创建新的进程*/

  if(pid<0)                                       /* 如果进程创建失败,输出错误信息并退出 */

  {

    printf("forkerror.\n");

    exit(1);

  }

  if(pid==0)                                      /* 子进程*/

    printf("Thisis the child process.\n");

  else                                                /*父进程 */

    printf("Thisis the parent process.\n");

  return 0;

}

 

编译命令:gcc  -o  process1 process1.c

命令说明:gcc  GNUC语言编译器,-o 后是可执行文件名

 

运行程序:/home/by-402/process1

运行结果:This is the child process

This is the parent process

 

2. /* example12-2.c 下面的程序使用wait( ) 将父进程阻塞,直到子进程执行结束。*/

#include <stdlib.h>

#include <stdio.h>

#include <unistd.h>

#include <sys/wait.h>                        

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值