Linux进程控制实验

实验1:该实验有3个进程,其中一个为父进程,其余两个是该父进程创建的子进程,其中一个子进程运行“ls -l”指令,另一个子进程在暂停5s之后异常退出,父进程先用阻塞方式等待第一个子进程的结束,然后用非阻塞方式等待另一个子进程的退出,待收集到第二个子进程结束的信息,父进程就返回。
Linux进程控制实验_第1张图片
实现代码:
/waitpid.c/
#include
#include
#include
#include
#include

int main(void)
{
pid_t pc,pr,q;
pc=fork();
pr=fork();
if(pc<0){
printf(“Error fork.\n”);
exit(1);
}
else if(pc==0){
printf(“child1 :execute ‘ls -l’\n”);
if(execlp(“ls”, “ls”, “-l”,NULL)<0){
printf(“child1 execlp error!\n”);

	     } 
	      }
if(pr<0){
	printf("Error fork.\n");
	exit(1);
                  }

            
else if(pr==0){ 
	printf("child2:sleep for 5 seconds\n");
	sleep(5);
	exit(0);
              }
    else{
           printf("father process!\n");
       q=waitpid(pc,NULL,0); /*zuseshi*/
	if(q==pc) 
			printf("The child1 process  finish!\n");
		
	else
		printf("error occured.\n");
                 
	     do{
		        q=waitpid(pr,NULL,WNOHANG);/*feizuseshi*/  
			if(q==0){
			printf("The child2 process has not ready\n");
			sleep(1);}
			else {q==0;}
	   }while(q==0);
	if(q==pr)
		printf("The child2 process finish!\n");
	else
		printf("error occured.\n");		
	
	} 
     exit(0);
        }

效果截图:
Linux进程控制实验_第2张图片
实验2:
在该实验中,读者首先建立起一个守护进程,然后在该守护进程中新建一个子进程,该子进程暂停10s,然后自动退出,并由守护进程收集子进程退出的消息。在这里,子进程和守护进程的退出消息都在系统日志文件(例如“/var/log/messages”,日志文件的全路径名因版本的不同可能会有所不同)中输出。子进程退出后,守护进程循环暂停,其间隔时间为10s。
Linux进程控制实验_第3张图片

实现代码:
#include
#include
#include
#include
#include
#include
#include

int main(void)
{
pid_t child1,child2;
int i;

child1 = fork();
if (child1 == 1)
{
perror(“child1 fork”);
exit(1);
}
else if (child1 > 0)
{
exit(0);
}

openlog(“daemon_wzb_info”, LOG_PID, LOG_DAEMON);

setsid();
chdir("/");
umask(0);
for(i = 0; i < getdtablesize(); i++)
{
close(i);
}

child2 = fork();
if (child2 == 1)
{
perror(“child2 fork”);
exit(1);
}
else if (child2 == 0)
{

syslog(LOG_INFO, " child2 will sleep for 10s ");
sleep(10);
syslog(LOG_INFO, " child2 is going to exit! ");
exit(0);
}
else
{
waitpid(child2, NULL, 0);
syslog(LOG_INFO, " child1 noticed that child2 has exited ");

closelog();
while(1)
{
sleep(10);
}
}
}
效果截图:
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(linux实验,linux,c++,多进程)