简体   繁体   中英

Hey, I wanna send an int array to a client process from the server process using shared memory, I'm not getting the expected output

#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 

int main()
{
 char c;
 int shmid;
 key_t key;
int *shm, *s;

int Arr[]={1,2,3,4,5,6,7,8};
int ArrySi=(sizeof(float)*8);
int x=8;
 key = 5680;

 if ((shmid = shmget(key, x, IPC_CREAT | 0666)) < 0) {
 perror("shmget");
 exit(1);
 }
 
 if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
 perror("shmat");
 exit(1);
 }
 
 s = shm;
 for (int i = 0; i < ArrySi; i++)
 {
    *s++ = Arr[i];
 }
 *s = NULL;
 while (*shm != '100')
 sleep(1);
 exit(0);
}

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 


int main()
{
 int shmid;
 key_t key;
 int *shm, *s;

int ArrySi=(sizeof(float)*8);
int x=8;

 key = 5680;

 if ((shmid = shmget(key,x, 0666)) < 0) {
 perror("shmget");
 exit(1);
 }
 if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
 perror("shmat");
 exit(1);
 }


 for (s = shm; *s != NULL; s++){
      printf("%d",*s);
 }
 printf("\n");

*shm = '100';

 exit(0);
}


12345678491876864327641979275776831294149-148692096022036-11741929743259849187687232764-11741934531-148692127122036 12345678491876864327641979275776831294149-148692096022036-11741929743259849187687232764-11741934531-148692127122036

Do not make up IPC keys at random. Instead do this:

key_t key = ftok( "/path/to/a/real/file", 'Z' );

It is a good idea to create a temporary file (known to both the server and client processes) and use its filename in the ftok(1) call. The last parameter can be any 8-bit value, as long as the server and client agree.

Your sentinel value ('100' ) is wrong. Single quotes translate into a character value and this tries to put at least 3 into it. C ain't Python.

There is not synchronization here for the SHM region creation, so you need to manually ensure the server process starts early enough before the client. Maybe put:

puts( "Start the client." );

before the sleep(3) wait loop in the server.

The online documentation in man(1) pages is intended as a memory aid, not a tutorial. Ask Mr. Google for an example to get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM