C++,是否有可能(以及如何)通过 exec() 运行 多动作、单行 curl 命令?

C++, is it possible (and how) to run a multi-action, one-liner curl command via exec()?

我有一个 curl 命令:

curl -c cookies.txt -b cookies.txt -k https://www.example.com/ajaxauth/login -d 'identity=email@example.com&password=pa$$w0rd&query=https://example.com/data/format/json' > ~/Documents/.../myProject/bin/data/myData.json"

那个

  1. 登录 API,
  2. 管理 cookie,
  3. 获取数据集并保存到本地文件。

我把它放在一个字符数组中并发送到 system() 命令,但是由于将变量(电子邮件和密码)传递给 system() 的危险,我必须使用 [=15] =] 代替。我不熟悉这个命令,文档让我感到困惑。所以我的问题:

这是我目前拥有的:

int pid = fork();

switch(pid){
    case -1:{            
        perror("fork"); // via 
        _exit(EXIT_FAILURE);
        break;
    }
    case 0:{ // child process
        //execv(cmd, ???);
        break;
    }
    default:{ // parent process                
        break;
    }
}

请注意,我无法使用 libcurl。任何帮助表示赞赏!

您可以使用 execlp 像这样拆分参数来执行您的命令(添加 NULL 以指示参数结束):

execlp("curl","curl","-c","cookies.txt","-b","cookies.txt","-k","https://www.example.com/ajaxauth/login","-d","identity=email@example.com&password=pa$$w0rd&query=https://example.com/data/format/json",NULL);

第一个参数是将从 PATH 中搜索的可执行文件,第二个参数在 manpage 中被引用为“按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。"

为了将 exec 的输出重定向到一个文件,您应该用输出文件替换标准输出:

int out = creat("myData.json", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
dup2(out,STDOUT_FILENO); 

全部放在一起:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

int main()
{   
    int pid = fork();
    switch(pid){
        case -1:{            
            perror("fork"); 
            _exit(EXIT_FAILURE);
            break;
        }
        case 0:{ // child process
            // create output file
            int out = creat("myData.json", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
            if (out == -1){
                perror("creat"); 
                _exit(EXIT_FAILURE);
            } else {
                // redirect stdout to output file
                dup2(out,STDOUT_FILENO); 
                // exec the command
                execlp("curl","curl","-c","cookies.txt","-b","cookies.txt","-k","https://www.example.com/ajaxauth/login","-d","identity=email@example.com&password=pa$$w0rd&query=https://example.com/data/format/json",NULL);
                // close output file
                close(out);
            }
            break;
        }
        default:{ // parent process                
            // wait for child process
            int status = 0;
            wait(&status);  
            printf("child status:%d\n",status);
            break;
        }
    }       
    return 0;
}