diff --git a/ex1/ex1.c b/ex1/ex1.c index c4b111641..819421d38 100644 --- a/ex1/ex1.c +++ b/ex1/ex1.c @@ -8,7 +8,24 @@ int main(void) { - // Your code here + int x = 100; + + printf("Parent PID: %d, x = %d \n", (int)getpid(), x); + + int rc = fork(); + + if (rc == 0) + { + printf("Fork successful. We are the child process.\n Child PID: %d, Parent PID: %d", getpid(), getppid()); + } + else if (rc > 0) + { + printf("We are the parent process.\n Parent PID: %d of Child PID: %d", getpid(), rc, x); + } + else + { + printf(stderr, "Fork failed"); + } return 0; } diff --git a/ex2/ex2.c b/ex2/ex2.c index 4245375b9..e6bc2670d 100644 --- a/ex2/ex2.c +++ b/ex2/ex2.c @@ -8,7 +8,25 @@ int main(void) { - // Your code here - + FILE *fptr; + fptr = fopen("text.txt", "w"); + + int rc = fork(); + + if (rc < 0) { // fork failed; exit + fprintf(stderr, "fork failed\n"); + exit(1); + } else if (rc == 0) { // child process satisfies this branch + printf("hello, child here (pid: %d) \n", (int) getpid()); + } else { + printf("hello, parent here (pid: %d) of child %d\n", (int) getpid(), rc); + } + + if (fptr == NULL) + { + printf("Error opening text file!"); + exit(1); + } + return 0; } diff --git a/ex3/ex3.c b/ex3/ex3.c index 3a3698c1f..1ded242dc 100644 --- a/ex3/ex3.c +++ b/ex3/ex3.c @@ -9,7 +9,22 @@ int main(void) { - // Your code here + int rc = fork(); + if (rc < 0) + { + fprintf(stderr, "Fork failed"); + exit(1); + } + else if (rc == 0) + { + printf("Hello from Child %d", (int) getpid()); + } + else + { + int wc = waitpid(rc, NULL, 0); //wait or child to terminate, dont care about status, no flags + printf("Goodbye from Parent %d of Child %d", (int) getpid(), rc); + } + return 0; } diff --git a/ex4/ex4.c b/ex4/ex4.c index 0221ca96e..11b508291 100644 --- a/ex4/ex4.c +++ b/ex4/ex4.c @@ -10,7 +10,19 @@ int main(void) { - // Your code here + int rc = fork; + + if (rc < 0) + { + fprintf(stderr, "Fork failed!\n"); + exit(1); + } + else + { + //execl("/bin/ls", "ls", NULL); + char *args[] = {"ls", "-l", NULL}; + execvp(args[0], args); + } return 0; } diff --git a/ex5/ex5.c b/ex5/ex5.c index cbf3b8e61..9bf72d734 100644 --- a/ex5/ex5.c +++ b/ex5/ex5.c @@ -16,7 +16,40 @@ char* msg3 = "hello world #3"; int main(void) { - // Your code here + printf("parent %d\n", (int) getpid()); + char inbuffer[MSGSIZE]; + int p[2]; + + if (pipe(p) < 0) + { + fprintf(stderr, "Pipe failure\n"); + exit(1); + } + int rc = fork(); + if (rc < 0) + { + fprintf(stderr, "Fork failure\n"); + exit(2); + } + else if (rc == 0) + { + printf("Child writing to pipe\n"); + write(p[1], msg1, MSGSIZE); + write(p[1], msg2, MSGSIZE); + write(p[1], msg3, MSGSIZE); + } + else + { + close(p[1]); //close write branch + wait(NULL); //not necessary b/c processes can run at same time but doesnt hurt + //ssize_t read(int fd, void *buf, size_t count); + for (int i = 0; i < 3; i++) + { + read(p[0], inbuffer, MSGSIZE); + printf("%s\n", inbuffer); + } + close(p[0]); //close read + } return 0; }