linus进程控制
1、fork()使用
创建新的进程子进程,用进程号来区分父子进程
#include<stdio.h>
#include<unistd.h>
int main()
{
int pid=fork();//创建子进程,然后给父进程返回进程号,
//给子进程返回0,创建失败则返回一个负数
if(pid<0) printf("进程创建失败");
else if(pid==0) printf{"我是子进程");//子进程进程号是0
else printf("我是父进程");//父进程进程号是一个非零正整数
return 0;
}
//输出顺序由系统对父子进程的调用顺序决定
2、exec()系统调用
执行成功后会用一个新的进程代替原进程,进程号不变,新的进程会覆盖原进程的的地址空间,所以在执行完成后不会接着exec()的下一条指令执行,执行成功后不会有返回,执行失败后会返回-1。
//范例
#include<unisd.h>
int main()
{
char*argv[]={"ls","-al","/etc/passwd",NULL};
execvp("ls",argv);
}
test1
//lab1.h文件
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <stdlib.h>
#include <wait.h>
#include <unistd.h>
typedef void (*sighandler_t)(int);
void showLs(){
printf("child one to continue\n");
}
//Lab1.c文件
#include "lab1.h"
int main(int argc, char *argv[])
{
int count = 0;
while (count <= 3)
{
pid_t pid1, pid2;
pid1 = fork();//create child one
signal(SIGINT, (sighandler_t)showLs);//register the processng interrupt function
int status;//child two status
if (pid1 < 0)
{ //failed to create child one
fprintf(stderr, "child one fork failed\n");
exit(-1);
}
else if (pid1 == 0)
{ /*child one*/
printf("I am child one process %d,my father is %d\n", getpid(), getppid());
pause();
printf("process %d is continue to run\n", getpid());
status=execlp("/bin/ls", "ls",NULL);
}
else
{
// father
printf("I am parent process %d\n ", getpid());
//child two
pid2 = fork();
if (pid2 < 0)
{ //failed to create child two
fprintf(stderr, "child two fork failed\n");
exit(-1);
}
else if (pid2 == 0)
{ //child two
printf("I am child two process %d,my father is %d\n", getpid(), getppid());
status = execlp("/bin/ps", "ps",NULL);
}
else
{ // father
waitpid(pid2, &status, 0);
kill(pid1, SIGINT);
}
/*all child process completed and exit*/
wait(NULL);
printf("cycle %d , all child process completed\n", count);
}
count++;
printf("\n");
printf("\n");
sleep(3);
}
}
head=lab1.h
srcs=lab1.c
objs=lab1.o
opts=-g -c
all:lab1
lab1:$(objs)
gcc $(objs) -o lab1
lab1.o:$(srcs) $(head)
gcc $(opts) $(srcs)
clean:
rm lab1*.o