c - 如何使用 execv 与 sudo 一起运行程序?

标签 c fork mpi execv

在提出这个问题之前,我阅读了很多帖子,不幸的是,他们都没有为我的问题提供所需的解决方案。 我正在使用 gnu c 编写一个 mpi 程序,并尝试在先前的子进程中执行 hping3 。 实际状态是,我可以生成一个子进程,也许可以执行 hping3 命令,但是子进程的管道输出给了我以下错误消息,该消息可能来自 hping3:

"you must specify only one target host at a time"

我做了以下事情: 首先,我创建了大量的字符数组来填充我的参数。 为什么是数组?我想在运行时更改端口和 IP(迭代循环)

//Parameter list for hping3 fork, maxlength precalculated (tcp restrictions and given params for hping)
char sudo[] = "/usr/bin/sudo";
char path[] = "/usr/sbin/hping3";
char scan[] = "--scan";
char port[] = "65535";
char ip[] = "192.168.111.111";
char verbose[] = "-V";
char *params[7];
params[0]=sudo;
params[1]=path;
params[2]=scan;
params[3]=port;
params[4]=ip;
params[5]=verbose;
params[6]=NULL;

参数的更改如下所示:

sprintf(*(params + 3), "%u", *(portarray+i));
sprintf(*(params + 4), "%u.%u.%u.%u", (iterator & 0xFF000000)>>24, (iterator & 0x00FF0000)>>16, (iterator & 0x0000FF00)>>8, (iterator & 0x000000FF));

最后是 fork 。

if(pid == -1){
               perror("Error forking");
            } else if(pid > 0){
               //Parent does not write
               close(pipes[1]);
               //Status Message
               printf("Pipe Output ...");
                fflush(stdout);
               //Parent, wait for child
               //waitpid(pid, &status, 0);
               //Save stdout from pipe
               while((nbytes = read(pipes[0], buffer+count, buffsize-count)) != -1) count+=nbytes;
               //Print out pipe
               printf("hping3: (%.*s)\n", nbytes, buffer);
               fflush(stdout);
               wait(NULL);
               close(pipes[0]);
            } else {
               //Child does not read
               close(pipes[0]);
               //Map stdout and stderr to write pipe-end
               dup2(pipes[1], STDOUT_FILENO);
               //dup2(pipes[1], STDERR_FILENO);

               //Status Message
               printf("Try to execute hping3 ...");
               fflush(stdout);

               //Child, exec hping with params
               execv("/usr/sbin/hping3",params);
               puts("never happens");
               close(pipes[1]);
               exit(1);
            }

非常感谢您的帮助,我有点陷入这个问题,现在已经研究了 12 个小时的解决方案。

最佳答案

此问题的有效解决方案是使用 execve。 它也可以与 execv 一起使用。 我必须使用完整路径调用 sudo 并将 hping3 及其参数传递给 sudo 命令。

//Child, exec hping with params
execve("/usr/bin/sudo",params, NULL);

关于c - 如何使用 execv 与 sudo 一起运行程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27844309/

相关文章:

c - 当通过 Socket 发送数据时,send/write 何时返回 -1?

c - strcmp 在 C 中导致段错误

子进程和父进程 ID

c - MPI发送/接收程序永远不会完成

计算斜边的 C 程序

c - 未定义对 main、makefile 的引用

python - Python Multiprocessing 如何在 Windows 上实现?

linux - fork() 之后的 libCurl SSL 错误

r - 从 R 调用并行 fortran MPI 子例程

mpi - Hydra MPI的最佳进步是什么