这是我的服务器的代码:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/fcntl.h>
#define FIFONAME "fifo_clientTOserver"
#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
int main(int argc, char *argv[])
{
// create a FIFO named pipe - only if it's not already exists
if(mkfifo(FIFONAME , 0666) < 0)
{
printf("Unable to create a fifo");
exit(-1);
}
/* make the key: */
key_t key;
if ((key = ftok("shmdemo.c", 'j')) == -1) {
perror("ftok");
exit(1);
}
else /* This is not needed, just for success message*/
{
printf("ftok success\n");
}
// create the shared memory
int shmid = shmget(key, sizeof(int), S_IRUSR | S_IWUSR | IPC_CREAT);
if ( 0 > shmid )
{
perror("shmget"); /*Displays the error message*/
}
else /* This is not needed, just for success message*/
{
printf("shmget success!\n");
}
// pointer to the shared memory
char *data = shmat(shmid, NULL, 0);
/* attach to the segment to get a pointer to it: */
if (data == (char *)(-1))
{
perror("shmat");
exit(1);
}
/**
* How to signal to a process :
* kill(pid, SIGUSR1);
*/
return 0;
}
我的服务器需要从共享内存段中读取一个 process-id (type pid_t
) 。
如何从共享内存段中读取某些客户端写入的数据?