【发布时间】:2025-12-19 13:55:07
【问题描述】:
我正在尝试将 samtools 的使用集成到 C 程序中。此application 以称为 BAM 的二进制格式读取数据,例如来自stdin:
$ cat foo.bam | samtools view -h -
...
(我意识到这是对 cat 的无用使用,但我只是展示了如何在命令行上将 BAM 文件的字节通过管道传输到 samtools。这些字节可能来自其他上游进程。)
在 C 程序中,我想将 unsigned char 字节块写入 samtools 二进制文件,同时在处理这些字节后从 samtools 捕获标准输出。
因为我不能使用popen() 同时对进程进行读写,所以我研究了使用popen2() 的公开可用实现,它似乎是为了支持这一点而编写的。
我编写了以下测试代码,它尝试将位于同一目录中的 BAM 文件的 write() 4 kB 块字节分配给 samtools 进程。然后它从samtools 的输出中将read()s 个字节放入行缓冲区,打印到标准错误:
#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 的本地副本,这是我用于测试的二进制文件的link。但任何 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.
如果我在write() 调用之后立即close() infp 变量,则循环在挂起之前再进行一次迭代:
...
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() 更适合此任务的方法?
【问题讨论】: