使用管道在 C 中写入 openssl 的 stdio

Writing to openssl's stdio in C using pipe

我正在尝试像这样将一些数据传递给 openssl:

int fd[2];
char buff[MAXBUFF];
pid_t childpid;
pipe(fd);

childpid = fork();

if (childpid == 0){
  dup2(0, fd[0]);
  close(fd[1]);
  execlp("openssl", "s_client", "-connect", "imap.gmail.com:993", "-crlf", NULL);
}
else {
  close(fd[0]);
  dosomething(buff);
  write(fd[1], buff, strlen(buff) + 1);
  sleep(4);
}

但 openssl 似乎没有从 buff 获取数据,我认为它只是挂起等待一些输入。 如果我对 bash

做同样的事情

a.sh:

.
.
.
echo $data
sleep 3
.
.
.

b.sh:

openssl s_client -connect imap.gmail.com:993 -crlf

./a.sh | ./b.sh

一切正常。

您切换了 dup2() 的参数。

原型为:

int dup2(int oldfd, int newfd);

所以你应该这样做

dup2(fd[0], 0);

设置fd[0]为子进程的标准输入。然后它应该按预期工作。