[英]realtime stream gpg encryption in c over pipe
我正在嘗試使用gpg實時加密數據。 我已經在直接使用libgcrypt,但是我需要標准格式。 我丟棄了gpgme,因為它似乎不適合實時流應用程序。
我想完成的是以下命令行:
gpg --passphrase hackerpass --symmetric -c
在終端中,它工作正常,打印頁眉,輸出數據,並以EOF CTRL-D結尾頁腳,完美!
這是示例代碼,簡單的fork,雙向管道,我編寫數據並異步等待結果, 但是 ... gpg的執行沒有結束,實際上似乎數據沒有到達,我只收到標頭,在fd關閉時gpg沒有收到EOF:
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[]) {
pid_t pid = 0;
int inpipefd[2];
int outpipefd[2];
char buf[256];
int status;
pipe(inpipefd);
pipe(outpipefd);
pid = fork();
if (pid == 0) {
// Child
dup2(outpipefd[0], STDIN_FILENO);
dup2(inpipefd[1], STDOUT_FILENO);
//dup2(inpipefd[1], STDERR_FILENO);
//ask kernel to deliver SIGTERM in case the parent dies
prctl(PR_SET_PDEATHSIG, SIGTERM);
execlp("/bin/sh", "/bin/sh", "-c", "/usr/bin/gpg --passphrase pass --symmetric -c", (char *) NULL);
exit(1);
}
//close unused pipe ends
close(outpipefd[0]);
close(inpipefd[1]);
int flags;
flags = fcntl(inpipefd[0], F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(inpipefd[0], F_SETFL, flags);
// write example data
char *data = "dummy dummy";
ssize_t out = write(outpipefd[1], data, strlen(data));
if (out != strlen(data)) {
printf("fail write\n");
exit(-1);
}
close(outpipefd[1]);
int hasPendingData = 1;
while (hasPendingData) {
ssize_t r = read(inpipefd[0], buf, 255);
if (r == -1 && errno == EAGAIN) {
// in process
printf("no data available, wait...\n");
usleep(500000);
} else if (r > 0) {
printf("Incoming %ld bytes\n", (long) r);
} else {
// EOF
hasPendingData = 0;
printf("no mode data available, exit...\n");
}
}
waitpid(pid, &status, 0);
return 0;
}
這里只是一個猜測,但是在子流程中您有幾個未關閉的重復文件描述符。 在這些文件描述符關閉之前,Gpg不會獲得EOF。 只要有可能向他們發送任何進程,它就會一直等待更多。
還要注意的另一件事是在編寫gpg阻塞,以等待進程讀取管道。 如果發生這種情況,那么您的寫作階段可能會受阻。 不會出現非常少量的數據,但是如果您放置任何卷,都可能在以后發生。 寫入和讀取都必須是非阻塞的,並且必須同時運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.