C程序,创建进程,PID

C program, creating processes , PID

任务如下

编写一个程序,将 运行 内存中的另一个进程并使其 运行 处于无限循环中。当程序重新启动时,它必须从内存中删除之前启动的进程(可以使用kill)。

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <spawn.h>
#include <sys/wait.h>

int main(void){
    int pid = getpid(); // we find out the PID of the current process and store it in a variable
    FILE *file = fopen("example.txt", "r"); // getting information from a file about a child process
    int filePid = 0;
    fscanf(file, "%d", filePid);
    fclose(file);
    
    switch (filePid){
        case -1:{ // if there is no child process, then run it and write the PID to a file
            filePid = fork();
            file = fopen("example.txt", "w");
            fprintf(file, "%d", filePid);
            fclose(file);
            break;
        }
        case 0:{ // if this process is a child, then we go into an infinite loop
            for(;;){
                sleep(7); // waiting for seven seconds so that the system is not heavily loaded
            }
            break;
        }
        default:{ // if this program is started again with a child process, then we send a signal to the child process
            kill(filePid, SIGKILL); // we send a signal to the child process so that it ends, and after that we write the information to the file
            file = fopen("example.txt", "w"); // we write information to the file that the child process is missing
            fprintf(file, "%d", -1);
            fclose(file);
        }
    }
    return EXIT_SUCCESS;
}

/是的,我必须通过qnx操作系统来完成。/

错误如下..我对getpid有点困惑,因为我没有在任何地方使用过pid变量。

还有一个错误。

我会感谢你的help.since我有点困惑...

UPD:

我无法获取值 0

UPD:它怎么能同时执行这两种情况,我的意思是同时执行“if”和“else”块?

how could it execute both cases, i mean "if" and "else" blocks at the same time?

您必须清楚地了解 fork 的工作原理,当您使用 fork 时,会创建两个相同的进程 parentchild 并且它们 运行 同时,当您说 filePid = fork() 并且如果操作成功,则 parent 进程将持有子进程的进程 ID,而 child 进程将持有 0。所以这里在父进程 filePid == child process ID 和子进程 filePid == 0.

man fork

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

所以你放在if (filePid == 0)块中的任何东西都会被子进程执行,而你放在else块中的任何东西都会同时被父进程执行。

This 如果您想了解更多 fork.

将会有所帮助

fork() 系统调用创建一个子进程和 return 它的 pid 所以一旦创建子进程你有两个进程 运行 在 fork() 之后一个相同的指令正在检查 pid更大,这意味着它的父级获得子 pid 并且在子上下文中 OS 将 pid 值设置为 0 因此它将进入用于子

的条件块