[英]Restart C program from Bash terminal
我一直在從事學校項目,現在已經在這一步驟上停留了幾天。 任何幫助將不勝感激!
到目前為止,我已經嘗試過:
這是我要做的:
使用C制作一個新文件。使用名稱
process.c
保存(此操作)#include <stdio.h> #include <unistd.h> int main() { printf("Creating a background process..\\n"); pid_t pid = fork(); if (pid > 0) return 0; /* Host process ends */ if (pid < 0) return -1; /* Forking didn't work */ while(1) { } /* While loop */ return 0; }
將以下代碼編譯到名為
process.o
工作程序中,然后啟動該進程。 (這樣做,到現在為止有效)使用
kill
命令重新啟動process.o
(殺死該進程有效,但不會重新啟動它)
您需要保持父進程運行以監視子進程。 如果父級檢測到該子級不再運行,則可以重新啟動它。
父母可以使用wait
系統調用來檢測孩子何時退出。
while (1) {
pid_t pid = fork();
if (pid < 0) {
return -1;
} else if (pid > 0) {
// parent waits for child to finish
// when it does, it goes back to the top of the loop and forks again
wait(NULL);
} else {
// child process
while (1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.