gpt4 book ai didi

C-Execl系统调用

转载 作者:行者123 更新时间:2023-11-30 19:37:23 25 4
gpt4 key购买 nike

我尝试在子进程上使用 execl 执行函数,但它返回错误。这是我的代码:

pid_t Process = fork();
if(Process == 0){
execl("path/to/executable/executable", "executable", "function", "function_parameter", (const char*)NULL);
}
else if(Process < 0){ //do something
}
else
{
//parent
}

程序从标准输入读取命令(每个命令都是一个函数),“函数名称”和“函数参数”是输入。为了示例:

$ ./executable

Welcome to the program

functionN 2

(function N gets executed with 2 as a parameter)
$

有人可以帮我解决这个问题吗?

最佳答案

您需要将输入写入可执行文件的标准输入,因此您可能应该使用管道:

int p[2];
pipe(p); // Error check?

pid_t Process = fork();
if (Process < 0)
{
perror("fork()");
close(p[0]);
close(p[1]);
}
else if (Process == 0)
{
dup2(p[0], 0);
close(p[0]);
close(p[1]);
execl("path/to/executable/executable", "executable", (char *)NULL);
perror("executable");
exit(1);
}
else
{
close(p[0]);
write(p[1], "functionN 2\n", sizeof("functionN 2\n")-1);
close(p[1]);
int status;
pid_t corpse = wait(&status);
}

对于显示的代码,您需要 header <unistd.h><sys/wait.h> (除了 <stdio.h><stdlib.h> )。还有无数其他方法可以调用电话 functionN 2指定的;也许使用更正统:

char line[] = "functionN 2\n";

write(p[1], line, sizeof(line) - 1);

(请记住, sizeof() 在字符串文字中包含终止 null,或者在调整像 line 这样的字符串数组大小时;不应将其写入子级。)

可以说,您应该检查corpse值与 Process 匹配值(value)。你会循环直到你得到正确的尸体或者你得到一个错误指示没有更多的 child 。如果您还有尚未等待的父进程也启动了其他进程,这可以为您提供保护。您还应该考虑报告尸体及其退出状态,至少出于调试目的:

int status = 0;
pid_t corpse;

while ((corpse = wait(&status)) != Process && corpse != -1)
printf("Other child %d exited with status 0x%.4X\n", (int)corpse, status);
if (corpse == -1)
printf("Oops! Executable died and we did not get told!\n");
else
printf("Executable %d exited with status 0x%.4X\n", (int)corpse, status);

关于C-Execl系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39884894/

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