如何将输入发送到 C 中的进程?
How do I send input to a process in C?
我正在尝试 运行 git 从 C:
推送
system("git push");
当它要求
username:
password:
我想还给它一个用户名和一个 github 身份验证令牌。我将如何做到这一点?我试图四处寻找解决方案,但当我 Google 问题时,我似乎无法正确使用措辞。请注意,我将用户名和身份验证令牌存储在 char*
's:
中
char *username = "whatever";
char *token = "whatever";
system("git push");
execv can be used to accomplish this .
int execv(const char *file, char *const argv[]);
示例:
以下示例说明了使用 execv 执行 ls shell 命令:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
main()
{
pid_t pid;
char *const parmList[] = {"/bin/ls", "-l", "/u/userid/dirname", NULL};
if ((pid = fork()) == -1)
perror("fork error");
else if (pid == 0) {
execv("/bin/ls", parmList);
printf("Return not expected. Must be an execv error.n");
}
}
您可以根据您的代码进行更改
如果进程是使用system(char *command);
创建的,则无法将输入数据发送到进程(或者也许是可能的,但我认为太难了),您需要使用[=12创建一个新进程=]. (popen documentation here)。这是我写的一个小例子:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char username[] = "something";
char password[] = "something";
FILE *pf; // file descriptor of the git process
pf = popen("git push", "w"); // create git process in write mode
if (!pf) {
printf("Process couldn't be created!");
return 1;
}
// this will send username and password (and the '\n' char too) to the git process
fputs(username, pf);
fputs(password, pf);
pclose(pf); // close git process
return 0;
}
我正在尝试 运行 git 从 C:
推送system("git push");
当它要求
username:
password:
我想还给它一个用户名和一个 github 身份验证令牌。我将如何做到这一点?我试图四处寻找解决方案,但当我 Google 问题时,我似乎无法正确使用措辞。请注意,我将用户名和身份验证令牌存储在 char*
's:
char *username = "whatever";
char *token = "whatever";
system("git push");
execv can be used to accomplish this .
int execv(const char *file, char *const argv[]);
示例: 以下示例说明了使用 execv 执行 ls shell 命令:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
main()
{
pid_t pid;
char *const parmList[] = {"/bin/ls", "-l", "/u/userid/dirname", NULL};
if ((pid = fork()) == -1)
perror("fork error");
else if (pid == 0) {
execv("/bin/ls", parmList);
printf("Return not expected. Must be an execv error.n");
}
}
您可以根据您的代码进行更改
如果进程是使用system(char *command);
创建的,则无法将输入数据发送到进程(或者也许是可能的,但我认为太难了),您需要使用[=12创建一个新进程=]. (popen documentation here)。这是我写的一个小例子:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char username[] = "something";
char password[] = "something";
FILE *pf; // file descriptor of the git process
pf = popen("git push", "w"); // create git process in write mode
if (!pf) {
printf("Process couldn't be created!");
return 1;
}
// this will send username and password (and the '\n' char too) to the git process
fputs(username, pf);
fputs(password, pf);
pclose(pf); // close git process
return 0;
}