gpt4 book ai didi

c - 通过 C 打开应用程序

转载 作者:行者123 更新时间:2023-11-30 17:22:02 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的 C 程序,它执行 Python 脚本(并让它运行...)并自行关闭。

我尝试了以下命令,但在这两种情况下,C 程序仍然存在......

popen("sudo python /home/pi/main.py", "r");
system("sudo python /home/pi/main.py");

谢谢!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!已编辑!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

我根据您的评论尝试了此命令,但没有成功:

char *argv[] = {"/home/pi/main.py"};
execv("sudo python", argv);

有人可以帮忙吗?谢谢!

!!!!!!!!!!!!编辑2!!!!!!!!!!!!!!!

这就是我编译它的方式:

gcc -Wall restart.c -o safekill

这是C程序

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

my_popen(char cmd[])
{
FILE *fp;
char path[1035];

fp = popen(cmd, "r");

if (fp == NULL)
{
printf("Failed to run command\n");
exit(1);
}

//Read the output a line at a time - output it
while (fgets(path, sizeof(path)-1, fp) != NULL)
{
printf("%s", path);
}

pclose(fp);

}

int main()
{
my_popen("sudo killall python");
sleep(1);
my_popen("sudo killall raspivid");
sleep(1);

if(fork())
printf("Am I here?");
return 0;

char *file = "restart";
char *argv[] = {file, "-c", "sudo python main.py", NULL};
execvp(file, argv);
}

结果:它打印出我在这里并且不启动Python。真是令人沮丧......:-(

最佳答案

您需要将程序本身的文件名添加到参数列表(argv[0])中,并使用 NULL 指针终止参数列表。

示例:

#include <stdlib.h>
#include <unistd.h>

int main() {
if(fork())
return 0;
char *file = "python";
char *argv[] = {file, "-c", "import time; time.sleep(5); print 'Hello'", NULL};
execvp(file, argv);
}

预期行为:立即(父)程序终止,并在 5 秒后由子程序打印一个简短的 Hello

也许您需要以某种方式解决 sudo 问题,但这应该可以帮助您入门。

关于c - 通过 C 打开应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com