Pokud chceš posílat signály sám sobě, potřebuješ getpid(). Protože ale to cvičení řeší komunikaci mezi procesy, chceš ve skutečnosti signalizovat mezi rodiči a potomky. Funguje třeba toto:
#define _POSIX_C_SOURCE 199506L
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
static int pipefd[2];
static sigset_t sset;
static
void write_to_pipe()
{
size_t idx = 0;
int sigret;
FILE *fh;
char buf[151];
close(pipefd[0]);
if (sigwait(&sset, &sigret) != 0)
_exit(EXIT_FAILURE);
if (sigret != SIGUSR1)
_exit(EXIT_FAILURE);
fh = fopen("p1.txt", "r");
if (fh == NULL)
_exit(EXIT_FAILURE);
while (idx < sizeof(buf) - 1) {
if (fread(buf + idx, 1, 1, fh) != 1)
_exit(EXIT_FAILURE);
idx++;
if (buf[idx-1] == '\n')
break;
}
buf[idx + 1] = '\0';
write(pipefd[1], buf, idx);
close(pipefd[1]);
_exit(EXIT_SUCCESS);
}
static
void read_from_pipe()
{
char buf;
while (read(pipefd[0], &buf, 1) > 0)
putchar(buf);
close(pipefd[0]);
}
int main(int argc, char *argv[])
{
const char* textmsg = "P1 SA HLASI KU SLUZBE!";
pid_t child;
sigemptyset(&sset);
sigaddset(&sset, SIGUSR1);
sigprocmask(SIG_BLOCK, &sset, NULL);
if (pipe(pipefd) < 0) {
perror("Failed to create pipe");
exit(EXIT_FAILURE);
}
puts(textmsg);
child = fork();
if (child < 0) {
perror("Forking failed");
exit(EXIT_FAILURE);
}
if (child == 0) {
write_to_pipe();
} else {
close(pipefd[1]);
kill(child, SIGUSR1);
read_from_pipe();
wait(NULL);
}
puts("All done");
return EXIT_SUCCESS;
}