02
2014
05

UC编程7-进程创建函数fork/vfork 和 execl/信号signal的使用1

//myuc.h

#include<stdio.h>//io流
#include<stdlib.h>//标准库
#include<unistd.h>//uc标准头文件
#include<fcntl.h>//文件控制
#include<string.h>//c字符串
#include<sys/types.h>
#include<sys/mman.h>//内存映射
#include<sys/stat.h>//文件状态信息
#include<sys/wait.h>//进程等等
#include<dirent.h>//目录操作
#include<signal.h>//信号
#include<sys/time.h>//时间,计时器
#include<sys/ipc.h>//ipc进程间通信
#include<sys/shm.h>//共享内存段
#include<sys/msg.h>//消息队列

//exitwiat7.h

#include "myuc.h"
void fun_exit()//退出之前要执行的函数
{
sleep(1);
printf("call exit\n");
}
void testexit()
{
atexit(fun_exit);//注册退出前调用的函数
printf("begin\n");
//_exit(0);//立即退出
//exit(0);//在这里退出,退出前调用atexit()注册的函数
printf("end\n");
}
void testwait()
{
pid_t pid=fork();
if(pid==0){
printf("子进程%d运行\n",getpid());
sleep(2);
exit(120);
}
printf("父进程等待\n");
int status;
pid_t wpid=wait(&status);
printf("结束等待\n");
printf("wpid=%d\n",wpid);
if(WIFEXITED(status)){
printf("正常退出,退出码:%d\n",WEXITSTATUS(status));
}
}
void testwaitpid()
{
pid_t pid1,pid2;
pid1=fork();
if(pid1>0){
pid2=fork();
}
if(pid1==0){
printf("process 1:%d\n",getpid());
sleep(2);
printf("process 1:%dend\n",getpid());
exit(100);
}
else{
sleep(3);
}
if(pid2==0)
{
printf("process 2:%d\n",getpid());
sleep(1);
printf("process 2:%dend\n",getpid());
exit(200);
}
else{
sleep(3);
}
int status;
waitpid(-1,&status,0);//0为阻塞等待,WNOHANG为不阻塞
if(WIFEXITED(status)){
printf("exitcode:%d\n",WEXITSTATUS(status));
}
printf("end\n");
}
int main()
{
//testexit();
//testwait();
testwaitpid();
return 0;//退出前调用atexit()注册的函数
}

//proc7.c

#include "myuc.h"
int main()
{
printf("pid=%d\n",getpid());
sleep(3);
printf("over\n");
}
////gcc proc7.c -o proc

//vfork7.c

#include "myuc.h"
void test1()
{
pid_t pid=vfork();
if(pid==0)
{
printf("子进程运行\n");
sleep(2);
printf("子进程结束\n");
exit(0);
}
printf("父进程结束\n");
}
int main()
{
test1();
return 0;
}

//vforkexec7.c

#include "myuc.h"
void test1()
{
pid_t pid=vfork();//vfork()创建全新进程,占用父进程空间
//vfork()和exec结合使用才有意义
//execl("/bin/ls","ls","-l","./",NULL);
if(pid==0)
{
printf("子进程运行%d\n",getpid());
sleep(2);
printf("子进程结束\n");
printf("子进程调用execl(),归还父进程空间\n");
//execl("/bin/ls","ls","-l","./a.out",NULL);
execl("./proc","proc",NULL);//execl成功后,
//后面语句在execl失败才执行
printf("execl()结束\n");
exit(0);//归还父进程空间
}
printf("父进程结束\n");
}
int main()
{
test1();
return 0;
}

//signal7.c

#include "myuc.h"
void fa(int signum)
{
printf("接收到的信号:%d\n",signum);
}
void test1()
{
printf("pid=%d\n",getpid());
signal(SIGINT,fa);//修改SIGINT信号的处理方式为自定义处理
signal(SIGQUIT,SIG_IGN);//修改SIGQUIT信号的处理方式为忽略
if(signal(SIGFPE,fa)==SIG_ERR){//是否注册成功
perror("signal"),exit(-1);
}
while(1);
}
int main()
{
test1();
return 0;
}




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。