Skip to content

Instantly share code, notes, and snippets.

@ahmedengu
Last active April 6, 2016 22:31
Show Gist options
  • Save ahmedengu/8fca68c11c0f17bbc18e381357142825 to your computer and use it in GitHub Desktop.
Save ahmedengu/8fca68c11c0f17bbc18e381357142825 to your computer and use it in GitHub Desktop.
threads and fork example
#include <stdio.h>
int id;
int main() {
id = fork();
if (id == 0) {
printf("Child : Child ID: %d, Parent ID: %d\n", getpid(), getppid());
}
else {
printf("Parent : ID: %d, Child ID: %d\n", getpid(),id);
}
return 0;
}
#include<stdio.h>
#include <pthread.h>
#include <unistd.h>
int tmp1, tmp2, fileDescriptor[2];
char readBuffer[80], messageChild[] = "child";
int main() {
pipe(fileDescriptor);
tmp1 = fork();
if (tmp1 == 0) {
close(fileDescriptor[0]);
write(fileDescriptor[1], messageChild, sizeof(messageChild));
}
else if (tmp1 > 0) {
close(fileDescriptor[1]);
read(fileDescriptor[0], readBuffer, sizeof(readBuffer));
printf("c1 : %s\n", readBuffer);
}
tmp2 = fork();
if (tmp2 == 0) {
close(fileDescriptor[1]);
read(fileDescriptor[0], readBuffer, sizeof(readBuffer));
printf("c2 : %s\n", readBuffer);
}else if (tmp2 > 0) {
close(fileDescriptor[0]);
write(fileDescriptor[1], messageChild, sizeof(messageChild));
}
return 0;
}
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
pthread_t tid[2];
int fileDescriptor[2],i;
char message[] = "received", readBuffer[80];
void *function(void *args) {
if (pthread_equal(pthread_self(), tid[0])) {
if (fork() == 0) {
close(fileDescriptor[0]);
write(fileDescriptor[1], message, sizeof(message));
}
} else {
if (fork() == 0) {
close(fileDescriptor[1]);
read(fileDescriptor[0], readBuffer, sizeof(readBuffer));
printf("%s\n", readBuffer);
}
}
sleep(10);
return NULL;
}
int main() {
pipe(fileDescriptor);
for(i = 0 ; i < 2 ; i++){
if (pthread_create(&(tid[i]), NULL, &function, NULL) != 0) {
printf("failed\n");
}
else {
printf("created\n");
}
}
sleep(10);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment