linux学习笔记2

创建进程

  1. fork执行成功,向父进程返回子进程的pid,并向子进程返回,fork调用一次,会返回两次.
  2. fork创建的新进程是父进程的副本(把父进程的内存复制给子进程),除pid和ppid不一样.
  3. 父进程和子进程区别是,子进程没有继承父进程的超时设置/父进程创建的文件锁/未决信号
  4. fork的执行是无序的,无法预计是先执行

man fork描述

//所需头文件
#include <unistd.h>

//返回类型
pid_t fork(void);

fork执行

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc,char *argv[])
{
	pid_t child = fork();
	if(child == -1)
	{
	   printf("fork  failed!\n");
	   return -1;
	}
	if(child == 0)
	{
	   printf("id=%d  is child process!\n",getpid());
	}
	else
	{
	   printf("id=%d is parent process!\n",getpid());
	}
	return 0;
}


子进程是从fork之后开始执行

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

int main(int argc,char *argv[])
{	
	printf("begin!\n");
	pid_t child = fork(); //子进程是fork之后,开始执行的
	if(child == -1)
	{
	   printf("fork  failed!\n");
	   return -1;
	}
	if(child == 0)
	{
	   printf("id=%d  is child process!\n",getpid());
	}
	else
	{
	   printf("id=%d is parent process!\n",getpid());
	}
	printf("end!\n");
	return 0;
}


execve 替换进程(只有一个进程)

man execve

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc,char *argv[])
{
	char *args[] = {"/bin/ls","-l",NULL};
	printf("pid=%d\n",getpid());
	execve("/bin/ls",args,NULL);
	printf("pid=%d\n",getpid());  //这里不会执行,进程在execve执行的时候,已经替换为bin/ls
	return 0;
}

wait

man 2 wait

//所需头文件
#include <sys/types.h>
#include <sys/wait.h>

//参数及返回类型
pid_t wait(int *status);

wait 示例

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc,char *argv[])
{
	pid_t child = fork();
	int status;
	if( child == -1)
	{
		printf("fork failed!\n");
		return -1;
	}
	if(child == 0)
	{
		printf("child bengin!\n");
		sleep(10);       //子进程休眠10秒钟
		printf("childe end!\n");
		return 101;      //这里返回101只是为了测试
	}
	else
	{
		printf("parent begin!\n");
		wait(&status);  //等待子进程退出,并获取子进程返回的状态
		printf("child end_status=%d\n",WEXITSTATUS(status)); //wait的参数无法直接使用,需要宏转换之后使用
		printf("parent end!\n");
	}
}



秋风 2016-11-22