1/*
2 *  This program is free software; you can redistribute it and/or modify
3 *  it under the terms of the GNU General Public License version 2.
4 *
5 *  This program is distributed in the hope that it will be useful,
6 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
7 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
8 *  GNU General Public License for more details.
9 *
10 * Test that the removal of the memory object contents is postponed until all
11 * open and map references to the shared memory object have been removed.
12 */
13
14/* ftruncate was formerly an XOPEN extension. We define _XOPEN_SOURCE here to
15   avoid warning if the implementation does not program ftruncate as a base
16   interface */
17#define _XOPEN_SOURCE 600
18
19#include <stdio.h>
20#include <sys/mman.h>
21#include <sys/stat.h>
22#include <unistd.h>
23#include <string.h>
24#include <fcntl.h>
25#include <errno.h>
26#include "posixtest.h"
27
28#define BUF_SIZE 8
29#define SHM_NAME "posixtest_3-1"
30
31int main(void)
32{
33	int fd;
34	char *buf;
35
36	fd = shm_open(SHM_NAME, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
37	if (fd == -1) {
38		perror("An error occurs when calling shm_open()");
39		return PTS_UNRESOLVED;
40	}
41
42	if (ftruncate(fd, BUF_SIZE) != 0) {
43		perror("An error occurs when calling ftruncate()");
44		shm_unlink(SHM_NAME);
45		return PTS_UNRESOLVED;
46	}
47
48	if (shm_unlink(SHM_NAME) != 0) {
49		perror("An error occurs when calling shm_unlink()");
50		return PTS_UNRESOLVED;
51	}
52	/* Now, SHM_NAME is unlinked but there are open references on it */
53
54	buf = mmap(NULL, BUF_SIZE, PROT_READ, MAP_SHARED, fd, 0);
55	if (buf == MAP_FAILED && errno == EBADF) {
56		printf("The shared memory object was removed.\n");
57		return PTS_FAIL;
58	} else if (buf == MAP_FAILED) {
59		perror("An error occurs when calling mmap()");
60		return PTS_UNRESOLVED;
61	}
62
63	printf("Test PASSED\n");
64	return PTS_PASS;
65
66}
67