linux应用编程之进程编程

1 进程概念

在自身的虚拟空间中运行的占据系统资源的程序。

2 父子进程

fork一个进程以后,都将会产生一个子进程,这个子进程拷贝了父进程的资源(可以使用execve来覆盖父进程的运行代码)。

3 僵死进程

当子进程退出,而父进程并没有回收机制(收尸)或者显式的忽略该信号的话,子进程就将变成僵尸进程。

4 例子

1)

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

int main()
{
	pid_t chl_pid;
	int status;

	if((chl_pid = fork()) < 0)
	{
		printf("fork error\n");
		exit(-1);
	}
	else if(chl_pid >0)
	{
		/*	if parent dones't process the signal or ignore this signal,
		*	then child will be a zimble signal
		*	(of course,there will be another method to kill the zimble 
		*	process,which is kill the parent process,then the child 
		*	process will be adoptted to 1st process)
		*/
		printf("this is parent\nchild pid : %d",chl_pid);
		wait(&status);

		while(1);
	}
	else
	{
		printf("this is child\n");
	}
	return 0;
}

2)多个子进程

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


int main()
{
	int ret;
	int wait_ch1_status,wait_ch2_status; //wait for child process's signal
	pid_t pid_1,pid_2;

	if( (ret =fork()) == 0 )
	{
		printf("child 1 process\n");
		exit(1);
	}
	else
	{
		pid_1 = ret;
		printf("pid 1 :%d\n",pid_1);
		//father 
		if( (ret = fork()) ==0)
		{
			printf("child 2 process\n");
			exit(1);
		}
		else
		{
			pid_2 = ret;
			printf("pid 2:%d\n",pid_2);
			printf("parent process\n");
			waitpid(pid_1,&wait_ch1_status,P_PID);
			waitpid(pid_2,&wait_ch2_status,P_PID);
			while(1);
		}
	}
	

}

3) execve()

/* myecho.c  */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	printf("123\n");
	exit(0);
}

/* execve.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
	
	char *newargv[] = {"hello","world",NULL};
	char *env[] = {NULL};

	execve(argv[1],newargv,env);
	perror("execve");
	exit(EXIT_FAILURE);
}

编译后

执行  $  ./execve ./myecho 

打印123

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值