xref: /base/startup/init/test/exec_test/client.c (revision d9f0492f)
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15#include <errno.h>
16#include <string.h>
17#include <sys/socket.h>
18#include <sys/un.h>
19#include <unistd.h>
20#include "init_log.h"
21#include "init_socket.h"
22#include "securec.h"
23
24#define BUFFER_LENGTH 15
25#define ARG_COUNT 2
26
27int main(int argc, char* argv[])
28{
29    if (argc < ARG_COUNT) {
30        INIT_LOGE("Client need an argument");
31        return 0;
32    }
33    int sockFd = socket(PF_UNIX, SOCK_DGRAM, 0);
34    if (sockFd < 0) {
35        INIT_LOGE("Failed to create client socket");
36        return -1;
37    }
38    struct sockaddr_un addr;
39    bzero(&addr, sizeof(struct sockaddr_un));
40    addr.sun_family = PF_UNIX;
41    size_t addrLen = sizeof(addr.sun_path);
42    int ret = 0;
43    if (strcmp(argv[1], "server") == 0) {
44        ret = snprintf_s(addr.sun_path, addrLen, addrLen - 1, "/dev/unix/socket/serversock");
45        INIT_ERROR_CHECK(ret >= 0, return -1, "Failed to format addr");
46        if (connect(sockFd, (struct sockaddr *)&addr, sizeof(addr))) {
47            INIT_LOGE("Failed to connect socket: %d", errno);
48            close(sockFd);
49            return -1;
50        }
51    } else {
52        INIT_LOGE("input error, invalid server name");
53        close(sockFd);
54        return -1;
55    }
56    ret = write(sockFd, argv[ARG_COUNT], strlen(argv[ARG_COUNT]));
57    if (ret < 0) {
58        INIT_LOGE("Failed to write, errno = %d", errno);
59    }
60    close(sockFd);
61    return 0;
62}