[英]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");
}
我希望有一个人可以帮助我。 而且不,我不能使用任何其他语言,因为我使用树莓派,并且已经熟悉C。我不想学习任何其他语言。
问题是,有没有办法停止第一个程序的while(1)-Loop?
有没有办法从第一个程序停止while(1)-Loop?
一种方法是调用kill()
向进程发送SIGTERM
或SIGKILL
信号,这将导致程序退出。 但是,要做到这一点,您还需要要杀死的进程的进程ID,而调用system()
并没有提供该ID。 相反,您可以通过fork()
自己的进程并在子进程中调用exec()
(或其变体之一)来启动新程序,从而启动进程。 因此,您的代码将类似于:
pid_t child_pid = fork();
if (child_pid == 0) {
execl(command);
}
然后,当父进程想要停止子进程时,它可以执行以下操作:
kill(child_pid, SIGTERM); // or SIGKILL
阻止孩子
但是,使用信号杀死进程是一种非常钝的工具。 最好在两个进程之间安排一些其他的进程间通信方法,并让子进程检查来自父进程的消息,以告知其正常退出。
Caleb对我有很大帮助。 这并不是我想要的真正工作,但是我在ubuntuforums.org上找到了另一篇文章(关键字为:c pid_t fork kill exec)。 那是一个非常好的答案。 因此,感谢您的帮助Caleb。 应该投票赞成,但我的代表不够高。 非常抱歉。 但是它说已经被记录了。
因此,这里是帖子的链接: 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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.