src/t_enospc.c: Fix an error for the loop initialization declaration
[xfstests-dev.git] / src / af_unix.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /* Create an AF_UNIX socket.
3  * Copyright (C) 2017 Red Hat, Inc. All Rights Reserved.
4  * Written by David Howells (dhowells@redhat.com)
5  */
6
7 #include <stdarg.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <stdbool.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/socket.h>
18 #include <sys/un.h>
19
20 #define offsetof(TYPE, MEMBER)  ((size_t)&((TYPE *)0)->MEMBER)
21
22 int main(int argc, char *argv[])
23 {
24         struct sockaddr_un sun;
25         struct stat st;
26         size_t len, max;
27         int fd;
28
29         if (argc != 2) {
30                 fprintf(stderr, "Format: %s <socketpath>\n", argv[0]);
31                 exit(2);
32         }
33
34         max = sizeof(sun.sun_path);
35         len = strlen(argv[1]);
36         if (len >= max) {
37                 fprintf(stderr, "Filename too long (max %zu)\n", max);
38                 exit(2);
39         }
40
41         fd = socket(AF_UNIX, SOCK_DGRAM, 0);
42         if (fd < 0) {
43                 perror("socket");
44                 exit(1);
45         }
46
47         memset(&sun, 0, sizeof(sun));
48         sun.sun_family = AF_UNIX;
49         strcpy(sun.sun_path, argv[1]);
50         if (bind(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
51                 perror("bind");
52                 exit(1);
53         }
54
55         if (stat(argv[1], &st)) {
56                 fprintf(stderr, "Couldn't stat socket after creation: %m\n");
57                 exit(1);
58         }
59
60         exit(0);
61 }