C 在后台从其他程序启动程序并从程序中关闭它

C Start Program from other Program in Background and close it from the Program

我想在后台启动一个程序,它应该可以从第一个程序停止。 代码 vom 启动器 C 代码:

#include<stdio.h>
#include<stdlib.h>

int main() {
    char command[50];
    int i;

    for(i=0; i<10; i++)
    {
            snprintf(command, sizeof(command), "./test %i &", i);
            system(command);
    }
    printf("FERTIG\n");
}

这里是在这种情况下应该启动 10 次的代码: (后面的代码应该会大很多,会是另一个代码,但是会有一个while(1)代码,所以我会需要它。)

#include<stdio.h>

int main(int argc, char* argv[])
{
    int i;
    printf("argc: %i\n", argc);
    for(i=0; i < argc; i++)
    {
            printf("argv[%d]: %s\n", i, argv[i]);
    }
    printf("FERTIG\n");
    while(1)
            printf("DAUERSCHLEIFE");
}

希望有人能帮助我。不,我不能使用任何其他语言,因为我使用 raspberry pi,并且已经熟悉 C。我不想学习任何其他语言。

问题是,有没有办法停止第一个程序的 while(1) 循环?

is there a way to stop the while(1)-Loop from the first Program?

一种方法是调用kill() 向进程发送SIGTERMSIGKILL 信号,这应该会导致程序退出。但是,要做到这一点,您还需要要终止的进程的进程 ID,而调用 system() 不会给您。您可以通过 fork() 自己的进程并在 child 进程中调用 exec()(或其变体之一)来启动新程序来启动该进程。所以你的代码看起来像:

pid_t child_pid = fork();
if (child_pid == 0) {
    execl(command);
}

那么,当parent进程要停止child进程时,可以这样做:

kill(child_pid, SIGTERM);    // or SIGKILL

停止 child.

不过,使用信号终止进程是一种非常生硬的工具。最好在两个进程之间安排一些其他 inter-process 通信方法,并让 child 进程检查来自 parent 的消息,告诉它正常退出。

Caleb 帮了我大忙。这并不是我想要的,但我在 ubuntuforums.org 上找到了另一个 post(关键字是:c pid_t fork kill exec)。这是一个非常好的答案。所以感谢你的帮助 Caleb。应该投票赞成,但我的代表还不够高。非常抱歉。但是它说已经记录了

所以这里是 link 到 post:https://ubuntuforums.org/showthread.php?t=675734

这是代码:

#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>

int main()
{
    pid_t childPID = fork();

    if ( childPID == -1 )
    {
        printf( "failed to fork child\n" );
        _exit( 1 );
    }
    else if ( childPID == 0 )
    {
        char *args[] = { "test", "hello", "world", 0 };

        execv( "test", args );
    }

    while ( 1 )
    {
        printf( "Enter 'q' to kill child process...\n" );
//      char c = getchar();
        sleep( 10 );
        char c = 'q';
        if ( c == 'q' )
        {
            kill( childPID, SIGKILL );
            break;
        }

        sleep( 1 );
    }

    return 0;
}

希望其他也遇到这个问题的人,可以通过我的问答来解决。

但非常感谢 Caleb。