Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions exec_env.c
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Account for the return values after the child process finishes execution, we will need it for other things.

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include "main.h"

/**
* exec_env - function to execute environment variables
*/

void exec_env() {
char *command[] = {"sh", "-c", "env", NULL};
char **env = environ;

/* Create a child process */
pid_t pid = fork();

if (pid == 0) {
/* This is the child process */
execve("/bin/sh", command, env);
/* execve only returns if an error occurs */
perror("execve");
exit(EXIT_FAILURE);
} else if (pid < 0) {
/* Fork failed */
perror("fork");
exit(EXIT_FAILURE);
} else {
/* This is the parent process */
/* Wait for the child to complete */
waitpid(pid, NULL, 0);
}
}
25 changes: 25 additions & 0 deletions main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include "main.h"

/**
* main - function to execute environment variables
* @argc: number of arguments
* @argv: Array of strings containing command-line arguments.
* @environ: Array of strings representing the environment variables.
* Return: 0 on success
*/

int main(int argc, char **argv, char **environ) {
char **env = environ;

if (argc > 1 && strcmp(argv[1], "invoke_env") == 0) {
/* Print environment variables */
while (*env != NULL) {
printf("%s\n", *env);
env++;
}
} else {
exec_env();
}

return (0);
}
15 changes: 15 additions & 0 deletions main.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#ifndef MAIN_H
#define MAIN_H

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

extern char **environ;

void exec_env();

#endif