#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<ctype.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<errno.h>
#include<assert.h>
#define ERROR_MSG(x) fprintf(stderr, "%s\n", (x))
#define BUF_SIZE 1024
#define MAX_TASKS 10
typedef struct program_tag {
char** args; // array of pointers to arguments
int num_args; // number of arguments
int pid; // process ID of this program
int fd_in; // FD for stdin
int fd_out; // FD for stdout
} Program;
void start_program(Program *progs, int total, int cur)
{
// TODO
int i=0;
for(;i<total;i++){
if(i==cur){
}else{
}
}
}
int wait_on_program(Program *prog)
{
return 0;
}
void prepare_pipes(Program *prog, int num_programs)
{
// TODO
int i=0;
for(i=0;i<num_programs;i++){
prog[i].pid = i;
prog[i].fd_in = i-1;
prog[i].fd_out =i+1;
}
}
void cleanup_programs(Program *prog, int num_programs)
{
// TODO
for(int i=0;i<num_programs;i++){
free(prog->args[i]);
}
}
void init_program(Program *prog, int na)
{
// allocate memory for array of arguments
prog->args = malloc(na * sizeof(char *));
assert(prog->args != NULL);
prog->num_args = 0;
prog->pid = prog->fd_in = prog->fd_out = -1;
}
int main(int argc, char **argv)
{
Program progs[MAX_TASKS];
int num_programs;
if (argc <= 1) {
ERROR_MSG("Specify at least one program to run. Multiple programs are separate\
d by --");
exit(-1);
}
fprintf(stderr, "Parent started. pid=%d\n", getpid());
// Prepare programs and their arguments
num_programs = 0;
int cur_arg = 1;
while (cur_arg < argc) {
init_program(&progs[num_programs], argc);
int ia;
for (ia = 0; cur_arg < argc; cur_arg ++) {
if (!strcmp(argv[cur_arg], "--")) {
if (num_programs == MAX_TASKS - 1) {
ERROR_MSG("Too many programs.");
exit(-1);
}
if (cur_arg + 1 == argc) {
ERROR_MSG("The last program is empty.");
exit(-1);
}
cur_arg ++;
break;
}
progs[num_programs].args[ia++] = argv[cur_arg];
}
if (ia == 0) {
ERROR_MSG("Empty program.");
exit(-1);
}
progs[num_programs].args[ia] = NULL;
progs[num_programs].num_args = ia;
num_programs ++;
}
// Prepare pipes
prepare_pipes(progs, num_programs);
// spawn children
for (int i = 0; i < num_programs; i ++) {
start_program(progs, num_programs, i);
}
// wait for children
for (int i = 0; i < num_programs; i ++) {
fprintf(stderr, "Waiting for child %2d (%5d)...\n", i, progs[i].pid);
wait_on_program(&progs[i]);
}
// cleanup
cleanup_programs(progs, num_programs);
fprintf(stderr, "Everything is good.\n");
return 0;
}
求问四个关于管道的函数怎么写好,菜鸟一个,求问大神