我正在尝试将使用集成samtools
到 C 程序中。此应用程序以称为 BAM的二进制格式读取数据,例如:stdin
$ cat foo.bam | samtools view -h -
...
(我意识到这是cat
对samtools
.
在 C 程序中,我想将unsigned char
字节块写入samtools
二进制文件,同时samtools
在处理这些字节后捕获标准输出。
因为我不能使用popen()
同时写入和读取进程,所以我研究了使用公开可用的实现popen2()
,它似乎是为了支持这一点而编写的。
我编写了以下测试代码,它尝试将write()
位于同一目录中的 BAM 文件的 4 kB 块字节发送到samtools
进程。然后它read()
从输出的 s 字节samtools
到一个行缓冲区,打印到标准错误:
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define READ 0
#define WRITE 1
pid_t popen2(const char *command, int *infp, int *outfp)
{
int p_stdin[2], p_stdout[2];
pid_t pid;
if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
return -1;
pid = fork();
if (pid < 0)
return pid;
else if (pid == 0)
{
close(p_stdin[WRITE]);
dup2(p_stdin[READ], READ);
close(p_stdout[READ]);
dup2(p_stdout[WRITE], WRITE);
execl("/bin/sh", "sh", "-c", command, NULL);
perror("execl");
exit(1);
}
if (infp == NULL)
close(p_stdin[WRITE]);
else
*infp = p_stdin[WRITE];
if (outfp == NULL)
close(p_stdout[READ]);
else
*outfp = p_stdout[READ];
return pid;
}
int main(int argc, char **argv)
{
int infp, outfp;
/* set up samtools to read from stdin */
if (popen2("samtools view -h -", &infp, &outfp) <= 0) {
printf("Unable to exec samtools\n");
exit(1);
}
const char *fn = "foo.bam";
FILE *fp = NULL;
fp = fopen(fn, "r");
if (!fp)
exit(-1);
unsigned char buf[4096];
char line_buf[65536] = {0};
while(1) {
size_t n_bytes = fread(buf, sizeof(buf[0]), sizeof(buf), fp);
fprintf(stderr, "read\t-> %08zu bytes from fp\n", n_bytes);
write(infp, buf, n_bytes);
fprintf(stderr, "wrote\t-> %08zu bytes to samtools process\n", n_bytes);
read(outfp, line_buf, sizeof(line_buf));
fprintf(stderr, "output\t-> \n%s\n", line_buf);
memset(line_buf, '\0', sizeof(line_buf));
if (feof(fp) || ferror(fp)) {
break;
}
}
return 0;
}
(对于 的本地副本foo.bam
,这里是我用于测试的二进制文件的链接。但任何 BAM 文件都可以用于测试目的。)
编译:
$ cc -Wall test_bam.c -o test_bam
问题是程序在write()
调用后挂起:
$ ./test_bam
read -> 00004096 bytes from fp
wrote -> 00004096 bytes to samtools process
[bam_header_read] EOF marker is absent. The input is probably truncated.
如果close()
在调用infp
后立即调用变量write()
,则循环在挂起之前再进行一次迭代:
...
write(infp, buf, n_bytes);
close(infp); /* <---------- added after the write() call */
fprintf(stderr, "wrote\t-> %08zu bytes to samtools process\n", n_bytes);
...
随着close()
声明:
$ ./test_bam
read -> 00004096 bytes from fp
wrote -> 00004096 bytes to samtools process
[bam_header_read] EOF marker is absent. The input is probably truncated.
[main_samview] truncated file.
output ->
@HD VN:1.0 SO:coordinate
@SQ SN:seq1 LN:5000
@SQ SN:seq2 LN:5000
@CO Example of SAM/BAM file format.
read -> 00004096 bytes from fp
wrote -> 00004096 bytes to samtools process
通过此更改,如果我在命令行上运行,我会得到一些我希望得到的输出samtools
,但如前所述,该过程再次挂起。
如何popen2()
将数据以块的形式写入和读取到内部缓冲区?如果这是不可能的,是否有替代方案可以popen2()
更好地完成这项任务?