Linux(本笔记基于的版本为Ubuntu 14.04)- 23 进程

1 进程控制

  1. fork 函数


    新创建的子进程从fork函数下继续执行,子进程的fork返回值为0,表示创建子进程成功;父进程的fork函数返回值返回的是子进程的pid值。
    1. 创建一个进程,参考代码:
      #include <stdio.h>
      #include <unistd.h>
      #include <stdlib.h>
      
      int main(void)
      {
      
      	pid_t pid;
      
      	printf("xxxxx\n");
      	
      	pid = fork();
      	if(pid == -1)
      	{
      		perror("fork error!");
      		exit(1);
      	}else if(pid == 0)
      	{
      		printf("I' am child, pid = %u\n, ppid = %u\n", getpid(), getppid());
      	}else if(pid > 0)
      	{
      		printf("I' am father, pid = %u\n, ppid = %u\n", getpid(), getppid());
      		sleep(1);
      	}
      
      	printf("YYYYYYY\n");
      	return 0;
      }

      运行结果:

      留待问题:当没有sleep(1)时,输出其实是:

      循环创建五个进程代码问题:

      三个pid的示例般:
       


      故循环创建5个子进程的参考代码:

      #include <stdio.h>
      #include <unistd.h>
      #include <stdlib.h>
      
      int main(void)
      {
      	int i;
      
      	pid_t pid;
      
      	printf("xxxxx\n");
      
      	for(i=0; i<5; i++)
      	{
      		pid = fork();
      		if(pid == -1)
      		{
      			perror("fork error!");
      			exit(1);
      		}else if(pid == 0)
      		{
      			printf("I' am child, pid = %u\n, ppid = %u\n", getpid(), getppid());
      			break; // if this is a child pid then step out 'for'
      		}else if(pid > 0)
      		{
      			printf("I' am father, pid = %u\n, ppid = %u\n", getpid(), getppid());
      			sleep(1);
      		}
      	}	
      
      	printf("YYYYYYY\n");
      	return 0;
      }

      运行结果:
      (Ps:程序在执行时,由于是指令的形式,故实际的计算机系统中运行的这段for循环,看似是子进程一一创建的,其实在计算机中是同时创建的。故创建的那一时刻是5个子进程和父进程同时抢夺cpu资源。书《advanced programming unix environment》中有一个结论,尽管是同时抢夺cpu资源,可是父进程抢到的可能性更大。但理论上同时抢时,即谁都有可能抢到。)

  2. getuid函数

    打个比方:sudo apt-get install 时,有效用户是root,实际用户是当前环境下的。
  3. getgid函数

 

2 进程共享


ps:文件描述符就是那一个指针,故在程序未分叉前有一个文件描述符时,程序分叉后,由于是同一个指针,故父子进程共享它。这和多个进程拥有同一个文件描述符时,指向的是同一个文件 是一个道理。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值