/* p1.c -- test popen() for fdopen failure */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
/* SYNOPSIS: ./p1 [-e] 1|2|3 - argument -e injects error opening max. fdopen() */
int main(int argc, const char *argv[])
{
FILE *pipe;
char line[2048];
int func, n = 0;
if (argc < 2) return 0;
if (argc > 2 && *argv[1] == '-' && argv[1][1] == 'e') { /* inject error in system */
int fd;
FILE *iop;
argv++; argc--;
for (n = 0; (fd = dup(STDIN_FILENO)) >= 0; n++) {
/* open max streams to exhaust open streams */
if ((iop = fdopen(fd,"r")) == NULL) {
perror("fdopen ERROR\n");
break;
}
}
printf("Total files opened: %d\n",n);
n = 0;
}
func = atoi(argv[1]);
if (func == 1) {
puts("func 1; read from pipe");
fflush(stdout);
pipe = popen("echo hi there", "r");
if (pipe == NULL) { puts("popen FAILURE\n"); abort(); }
setbuf(pipe, NULL);
while(fgets(line, sizeof(line), pipe) != NULL && strlen(line) > 1) {
fprintf(stdout, "%3d %s", ++n, line);
fflush(stdout);
}
pclose(pipe);
} else if (func == 2) {
puts("func 2; write to pipe");
fflush(stdout);
pipe = popen("echo hi there", "w");
if (pipe == NULL) { puts("popen FAILURE\n"); abort(); }
setbuf(pipe, NULL);
while(fgets(line, sizeof(line), stdin) != NULL && strlen(line) > 1) {
fprintf(pipe, "%3d %s", ++n, line);
fflush(pipe);
}
pclose(pipe);
} else if (func == 3) {
puts("func 3; read and write pipe");
fflush(stdout);
pipe = popen("echo hi there", "r+");
if (pipe == NULL) { puts("popen FAILURE\n"); abort(); }
setbuf(pipe, NULL);
while(fgets(line, sizeof(line), pipe) != NULL && strlen(line) > 1) {
fprintf(pipe, "%3d %s", ++n, line);
fflush(pipe);
}
pclose(pipe);
}
return 0;
}
/* p1.c end */