#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
// Child process
printf("I am the child, pid: %d\n", getpid());
} else {
// Parent process
printf("I am the father, pid: %d\n", getpid());
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
// Child process
execlp("ps", "ps", "-A", NULL);
perror("execlp"); // This will be executed only if execlp fails
exit(EXIT_FAILURE);
} else {
// Parent process
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("child over\n");
} else {
fprintf(stderr, "Child process did not terminate normally\n");
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_INPUT_LENGTH 1024
void display_prompt() {
printf("%s", "% ");
}
int main() {
char input[MAX_INPUT_LENGTH];
while (1) {
display_prompt();
if (fgets(input, sizeof(input), stdin) == NULL) {
fprintf(stderr, "Error reading input\n");
exit(EXIT_FAILURE);
}
// Remove newline character from input
input[strcspn(input, "\n")] = 0;
if (strcmp(input, "exit") == 0 || strcmp(input, "logout") == 0) {
break;
}
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
execlp(input, input, NULL);
perror("execlp"); // This will be executed only if execlp fails
exit(EXIT_FAILURE);
} else {
// Parent process
int status;
waitpid(pid, &status, 0);
if (!WIFEXITED(status)) {
fprintf(stderr, "Child process did not terminate normally\n");
}
}
}
return 0;
}