[go: up one dir, main page]

0% found this document useful (0 votes)
6 views4 pages

Program Embedded LinuxProject

Uploaded by

Nimish Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Program Embedded LinuxProject

Uploaded by

Nimish Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

#include <stdio.

h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

int number;
int square;

void* thread1_func(void* arg) {


int num = *((int*)arg);
square = num * num;
printf("In thread 1: square = %d\n", square);
pthread_exit(NULL);
}

void* thread2_func(void* arg) {


int num = *((int*)arg);
int* result = malloc(sizeof(int));
*result = num + square;
printf("In thread 2: square of num + num = %d\n", *result);
pthread_exit((void*)result);
}

int main() {
pid_t pid;
char *fifo = "/tmp/myfifo";
printf("[main] Creating FIFO (if not exists)...\n");
mkfifo(fifo, 0666);

printf("[main] Forking child process...\n");


pid = fork();

if (pid == 0) {
printf("[child] Executing programFIFO...\n");
execl("./programFIFO", "programFIFO", NULL);
perror("[child] execl failed");
exit(1);
} else {
printf("[main] Opening FIFO to read input from child...\n");
int fd = open(fifo, O_RDONLY); // open FIFO before wait
if (fd == -1) {
perror("[main] Failed to open FIFO");
exit(1);
}

printf("[main] Waiting for child to finish...\n");


wait(NULL);

read(fd, &number, sizeof(number));


printf("[main] Received number: %d\n", number);
close(fd);

pthread_t thread1, thread2;


void* final_result;

pthread_create(&thread1, NULL, thread1_func, &number);


pthread_join(thread1, NULL);
pthread_create(&thread2, NULL, thread2_func, &number);
pthread_join(thread2, &final_result);

printf("[main] Final result from thread2: %d\n", *((int*)final_result));


free(final_result);
}

return 0;
}

// programFIFO.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
int num;
printf("ProgramFIFO:\nEnter a number: ");
scanf("%d", &num);

char *fifo = "/tmp/myfifo";


int fd = open(fifo, O_WRONLY);
if (fd == -1) {
perror("open");
exit(1);
}

write(fd, &num, sizeof(num));


close(fd);

return 0;
}

all: programMain programFIFO

programMain: programMain.c
gcc -o programMain programMain.c -lpthread

programFIFO: programFIFO.c
gcc -o programFIFO programFIFO.c

clean:
rm -f programMain programFIFO

You might also like