Linux进程编程实战

1、获取进程的PID

函数原型:pid_t getpid();
作用:获取当前进程的pid

函数原型:pid_t getppid();
作用:获取当前进程的父进程的pid

代码:
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	pid_t pid = 0;

	pid = getpid();

	printf("my pid is:%d\n",pid);

	while(1);

	return 0;
}

2、进程的创建实战
使用fork函数创建一个进程
函数原型:pid_t fork(void);

fork函数调用成功,返回两次
返回值为0, 代表当前进程是子进程
返回值非负数,代表当前进程为父进程

调用失败,返回-1

代码:
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	pid_t pid;
	
	int data = 10;	

	printf("father pro pid is: %d\n",getpid());

	pid = fork();


	if(pid > 0){
		printf("this is father pro printf,pid: %d\n",getpid());
	}else if(pid == 0){
		printf("this is child pro printf,pid: %d\n",getpid());
		data = data + 10;
	}

	printf("data = %d\n",data);
	
	return 0;
}

3、用进程模拟客户端接入服务器
代码:

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

int main()
{
	pid_t pid;
	
	int data;
	
	while(1){
	
		printf("please input a data:\n");
		scanf("%d",&data);

		if(data == 1){
						
			pid = fork();


			if(pid > 0){
				//printf("this is father pro printf,pid: %d\n",getpid());
			}else if(pid == 0){
				while(1){
					printf("do net request!,pid: %d\n",getpid());
					sleep(3);
				}
			}
		}else{
			
			printf("wait ,do nothing!\n");
		}	

	}


	
	return 0;
}

4、孤儿进程实验
父进程如果不等待子进程退出,在子进程之前就结束了自己的“生命”,此时子进程叫做孤儿进程

Linux避免系统存在过多孤儿进程,init进程收留孤儿进程,变成孤儿进程的父进程

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

int main()
{
	pid_t pid;
	
	int cnt = 0;	
	

	pid = fork();


	if(pid > 0){
			
			printf("this is father pro printf,pid: %d\n",getpid());
		
	}else if(pid == 0){
		while(1){
			printf("this is child pro printf,childpid: %d,myfatherpid:%d\n",getpid(),getppid());
			sleep(1);
			cnt++;
			if(cnt == 3)
		//	_exit(0);
	//		_Exit(0);
			exit(3);
		}

	}


	return 0;
}

5、exec族函数
https://blog.csdn.net/u014530704/article/details/73848573

6、system函数
int system(const char *command);
system()函数的返回值如下:
成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;

https://www.cnblogs.com/leijiangtao/p/4051387.html

7、popen函数
https://blog.csdn.net/libinbin_1014/article/details/51490568

比system在应用中的好处:
可以获取运行的输出结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值