汰仁須 (tanisnikana) wrote in e2_geeks,
汰仁須
tanisnikana
e2_geeks

  • Mood:

C, to be compiled in gcc under cygwin. This is supposed to take the command line arguments and have the parent send them over, char by char to the child, where the child counts them and prints the number. But something's not right...

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

#define PARENT_FINISHED	-5
#define READ_ERR	-6
#define WRITE_ERR	-7

static int		toChild[2];		// pipe to child
static int		fromChild[2];		// pipe from child
static int		in, out;		// file descriptors for processes to use

char readPipe ()
{
	char	ch;
	
	if (read(in, &ch, 1) == 1)
		return ch;
	else {
		printf("readPipe: read error\n");
		exit(READ_ERR);
		}
}

void writePipe (char ch)
{
	if (write(out, &ch, 1) != 1) {
		printf("writePipe: write error\n");		
		exit(WRITE_ERR);
		}
}

int main (int argc, char **argv)
{
	pid_t	pid;
	char	ch;
	int 	charCounter;
	int 	status;

	printf("CS271 - Tanis Nikana - Assignment 01\n");

	// set up pipe to child
	if (pipe(toChild)) {
		printf("pipe to child: error\n");
		return -1;
		}

	// set up pipe from child
	if (pipe(fromChild)) {
		printf("pipe from child: error\n");
		return -1;
		}

	pid = fork();

	if (pid < 0) {
		printf("Fork error %d\n", pid);
		return -1;
	}

	if (pid == 0) { //child 
		close(fromChild[0]);
		out = fromChild[1];
		in = toChild[0];
		close(toChild[1]);
		while ((ch = readPipe()) != PARENT_FINISHED){
			charCounter++;
			printf("Child received a %c \n", ch);
			sleep(1);
		}
		printf("Child received PARENT_FINISHED signal.\n");
		printf("Child received %d characters.\n", charCounter);
		return 555;	
		
	}

	if (pid != 0) { //parent 
		int	i = 1; // loop index
		int	j = 0; // inner index
		close(toChild[0]);
		out = toChild[1];
		in = fromChild[0];
		close(fromChild[1]);
		//new write commands go here
		for (i = 1; i < (argc - 1); i++)
			for (j = 0; j > strlen(argv[i]); j++)
				writePipe(argv[i][j]);

		writePipe(PARENT_FINISHED);
		printf("Parent sent PARENT_FINISHED signal.\n");
		waitpid(pid, &status, 0);
		printf("Parent reaps child with 0x%08X\n", status);
		if (WIFEXITED(status))
			printf("Parent reports that child exited normally with %d\n", WEXITSTATUS(status));
		printf("Parent exits.\n");
		return 0;
	}
	return (0);
}
  • Post a new comment

    Error

    default userpic
  • 0 comments