From b304263af03a4ca7f886d0d00e67aea466ddbbdc Mon Sep 17 00:00:00 2001 From: John Breaux Date: Mon, 21 Feb 2022 19:26:52 -0600 Subject: [PATCH] Makefile: make file syscalls: Solve question 2 --- Makefile | 19 +++++++++++++++++++ syscalls.c | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 Makefile create mode 100644 syscalls.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..95ad556 --- /dev/null +++ b/Makefile @@ -0,0 +1,19 @@ + +CC = gcc +CFLAGS = + +OBJECTS := syscalls.o +EXEC := syscalls + +.PHONY: all clean + +all: $(EXEC) + +%: %.o + $(CC) $(CFLAGS) -o $@ $^ + +%.o: %.c + $(CC) $(CFLAGS) -c -o $@ $< + +clean: + rm $(OBJECTS) $(EXEC) \ No newline at end of file diff --git a/syscalls.c b/syscalls.c new file mode 100644 index 0000000..3042d54 --- /dev/null +++ b/syscalls.c @@ -0,0 +1,40 @@ +/* +-----------------------------------------------+ + | John Breaux - jab0910 - JohnBreaux@my.unt.edu | + | syscalls.c - CSCE4600 Homework 1 Question 2 | + +-----------------------------------------------+ */ + +#include // wait() +#include // fork(), getpid(), getppid(), execl(), exit() +#include // EXIT_SUCCESS +#include // printf() +// tabs are 3 spaces, because I find it more aesthetically pleasing than x=[1-8]|x!=3 spaces +int main(int argc, char **argv) { + // First we fork, and assign the child's pid to a variable + int child = fork(); + // If we have a child, then we're the parent, and must wait for the child to execute + if (child) { + // We get our own pid + int pid = getpid(); + printf("[PARENT]: pid = %d, child = %d\n", pid, child); + // Wait for the child to exit, and acquire its status + int status = 0; + int exited_child = wait(&status); + printf("[PARENT]: child %d exited with status %d.\n", exited_child, status); + // exit + exit(EXIT_SUCCESS); + } + // If we have no child, we are the child, and are assigned the task of executing + else { + // Get our pid, get parent's pid + int pid = getpid(), parent_pid = getppid(); + // Print that information + printf("[CHILD ]: pid = %d, parent_pid = %d\n", pid, parent_pid); + // Hand control over to ls, with the arguments "-la" + char *command = "/bin/ls", *argv1 = "-la"; + printf("[CHILD ]: execl(%s, %s, NULL);\n", command, argv1); + // execl takes the command, the arguments, and a null-pointer terminator argument + // argv[0] is the path to the command, argv[1] is the first argument + // personally I prefer execv()/execve() for their relative ease of use + execl(command, command, argv1, (char*)NULL); + } +}