Я работал над этим проектом fork (). Я работаю по мере необходимости, когда все закодировано в main (), но я хочу, чтобы каждый дочерний элемент вызывал свою функцию из отдельного файла, а не в main (). Я связал их в библиотеке stati c. Я не получаю ошибок или предупреждений при компиляции, но когда я запускаю, я получаю интересный вывод.
Конечная цель - перейти к именованным каналам с этими тремя отдельными файлами. Но я хочу понять, как это работает.
Текущий main ():
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#include <time.h>
#define MAX 180
#define PipeStdIn 0 //UNIX StdIn
#define PipeStdOut 1 //UNIX StdOut
void lifeSupport();
void navigation();
int main()
{
const char *message = {"Calibrate Systems\n"};
int pipes[2], ret;
char buf[MAX + 1];
if(pipe(pipes) == 0)
{
if(fork() == 0)
{
lifeSupport();
}
else
{
ret = write(pipes[PipeStdOut], message, strlen(message) + 1); //write
ret = wait(NULL);
ret = read(pipes[PipeStdIn], buf, MAX);
time_t now;
time(&now);
printf("Report received: %s\n", buf);
printf("Report time: %s\n", ctime(&now));
if(fork() == 0)
{
navigation();
}
else
{
ret = write(pipes[PipeStdOut], message, strlen(message) + 1); //write
ret = wait(NULL);
ret = read(pipes[PipeStdIn], buf, MAX);
time_t now;
time(&now);
printf("Report received: %s\n", buf);
printf("Report time: %s\n", ctime(&now));
}
}
}
close(pipes[PipeStdIn]);
close(pipes[PipeStdOut]);
return 0;
}
Текущая функция lifeSupport:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#include <time.h>
#define MAX 180
#define PipeStdIn 0 //UNIX StdIn
#define PipeStdOut 1 //UNIX StdOut
void lifeSupport()
{
int pipes[2], ret;
char buf[MAX + 1];
ret = read(pipes[PipeStdIn], buf, MAX); //read
printf("Life Support receives instruction: %s\n", buf); //notification confirming life support has received the command from parent
sleep(5); //5 second sleep to simulate adjustment of breathing gas levels
sleep(4); //4 second sleep to simulate adjustment of lighting and temp levels
//message informing that the levels have completed adjusting
const char *breathGL = {"Breathing gas levels have been adjusted\n\t\t Adjustment time: 5 seconds\n\t\t Lighting and temperture levels have been adjusted\n\t\t Adjustment time: 4 seconds"};
ret = write(pipes[PipeStdOut], breathGL, strlen(breathGL) + 1); //write
}
Текущая функция навигации:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#include <time.h>
#define MAX 200
#define PipeStdIn 0 //UNIX StdIn
#define PipeStdOut 1 //UNIX StdOut
void navigation()
{
printf("test");
int pipes[2], ret;
char buf[MAX + 1];
ret = read(pipes[PipeStdIn], buf, MAX); //read
//notification confirming navigation has received the command from parent
printf("\nNavigation receives instruction: %s\n", buf);
//generates a random number between 0 & 6 to use as simulated adjustment time
sleep(rand() % 7);
//message informing that the levels have completed adjusting
const char *nav = {"Navigation system has been adjusted\n\t\t Adjustment time: 0-6 seconds"};
ret = write(pipes[PipeStdOut], nav, strlen(nav) + 1); //write
}
Ожидаемый результат:
Life Support receives instruction: Calibrate Systems
Report received: Breathing gas levels have been adjusted
Adjustment time: 5 seconds
Lighting and temperture levels have been adjusted
Adjustment time: 4 seconds
Report time: Tue Apr 28 09:50:47 2020
Navigation receives instruction: Calibrate Systems
Report received: Navigation system has been adjusted
Adjustment time: 3 seconds
Report time: Tue Apr 28 09:50:50 2020
Текущие неверные результаты:
Life Support receives instruction: ���
Report received: Calibrate Systems
Report time: Tue Apr 28 23:34:11 2020
В этот момент он зависает, и я должен нажать Ctrl + c, чтобы остановить его.
Я все еще очень плохо знаком с fork (), поэтому я предположил, что смогу вызвать такую функцию. Очевидно, в этом есть что-то большее, и я не смог понять это.