問題描述
參考以上示例程序中建立併發進程的方法,編寫一個父子協作進程,父進程創建一個子進程並控制它每隔 3 秒顯示一次當前目錄中的文件名列表。
設計思路
由父進程創建子進程,父進程等待子
進程的完成,子進程中執行 ls 命令再次創建了子進程 ps(不必須要創建兩個子進程),之後也是等待子進程的執行,子進程完成 ls 命令後,由於信號量 sleep(3)的設置,間隔 3秒後再次執行該程序,如此循環,直到手動停止。
程序實現
Pctl.c
#include "pctl.h"
int main(int argc, char *argv[])
{
char *args[] = {"/bin/ls","-a",NULL}; //子進程要缺省執行的命令
int pid_1,pid_2; //存放子進程號
int status_1,status_2; //存放子進程返回狀態
while(1){
pid_1=fork() ;
if(pid_1<0) // 建立子進程失敗?
{
printf("Create Process fail!\n");
exit(EXIT_FAILURE);
}
if(pid_1 == 0) // 子進程執行代碼段
{
//報告父子進程進程號
printf("I am Child-ls process %d\nMy father is %d\n",getpid(),getppid());/*getpid 返回當前進程
的進程號,getppid 返回當前進程父進程的進程號*/
pid_2=fork();
if(pid_2<0)// 建立子進程失敗?
{
printf("Create Process fail!\n");
exit(EXIT_FAILURE) ;
}
if(pid_2==0) // 子進程執行代碼段
{//報告父子進程進程號
printf("I am Child-ps process %d\nMy father is %d\n",getpid(),getppid());
printf("%d child will Running: \n",getpid()); /*子進程被鍵盤中斷信號喚醒繼續執行*/
status_2=execve("/bin/ps",NULL,NULL);//裝入並執行新的程序
}else{
printf("wait for the ps-child end%d\n",pid_2);
waitpid(pid_2,&status_2,0);//等待子進程 2 結束
//status 用於保留子進程的退出狀態
}
printf("%d child will Running: \n",getpid()); //裝入並執行新的程序 char *argv[]={"0",NULL};
status_1 = execve("/bin/ls",argv,NULL);
}
else{
printf("I am Parent process %d\n",getpid());
printf("wait for the ls-child end %d\n",pid_1);
waitpid(pid_1,&status_1,0);
printf("child end,sleep...\n");
sleep(3);// sleep 函數會令調用進程的執行掛起睡眠 3 秒
}
}
return EXIT_SUCCESS;
}
運行