'Linux API'에 해당되는 글 135건

  1. 2023.10.19 malloc() 으로 할당된 메모리 리스트?
  2. 2023.07.21 bind(): Address already in use
  3. 2023.06.23 recv 와 read 차이
  4. 2023.06.21 inotify
  5. 2023.01.09 system v shmget size
  6. 2022.11.28 segfault시 calltree 출력하기
  7. 2022.11.24 pthread 테스트
  8. 2022.11.23 pthread
  9. 2022.11.11 iio(industrial io) 문서
  10. 2022.10.26 mkpipe 와 poll
Linux API/linux2023. 10. 19. 16:21

관용적으로 malloc() 해서 받은 인자가 0인지 확인하고(fail)

그 값을 포인터에 넣고 썼을 뿐이고, free() 하면서 null 값을 넣어주곤 했는데

반대로 system call이나 라이브러리를 이용하여

현재 사용중인 프로그램에서 malloc()을 요청해서 관리중인 리스트 이런건 구할 수 없는건가?

조사가 필요한 듯..

 

[링크 : https://www.gnu.org/software/libc/manual/html_node/Memory-Allocation-Probes.html]

[링크 : https://www.reddit.com/r/cpp_questions/comments/pi8lhg/how_do_i_check_if_a_pointer_is_valid/]

[링크 : https://stackoverflow.com/questions/993324/how-to-check-if-a-pointer-is-valid]

[링크 : https://stackoverflow.com/questions/5716100/what-happens-in-the-kernel-during-malloc]

'Linux API > linux' 카테고리의 다른 글

/proc/uptime  (0) 2023.10.24
/proc/pid/statm  (0) 2023.10.23
inotify  (0) 2023.06.21
system v shmget size  (0) 2023.01.09
segfault시 calltree 출력하기  (0) 2022.11.28
Posted by 구차니
Linux API/network2023. 7. 21. 18:56

libmodbus 사용하면 희한하게 일정 시간 이후에나 해당 소켓이 사용가능하도록 풀리는데

libmodbus가 종료시 제대로 bind를 풀어주지 않아 발생하는 것으로 예측만 했는데, 일단은~ 회피법을 찾은 듯.

 

SO_REUSEADDR

[링크 : https://www.inflearn.com/questions/20648/%EC%97%90%EB%9F%AC-bind-address-already-in-use]

 

딱 내가 겪고 있던 증상

이는 기존 프로그램이 종료되었지만, 비정상종료된 상태로 아직 커널이 bind정보를 유지하고 있음으로 발생하는 문제다. 보통 1-2분 정도 지나만 커널이 알아서 정리를 하긴 하지만, 그 시간동안 기달려야 한다는 것은 상당히 번거로운 일이다. 이 경우 다음과 같은 코드를 삽입함으로써 문제를 해결할 수 있다.

int sock = socket(...);
setsockopt(sockSOL_SOCKETSO_REUSEADDR, (char *)&bf, (int)sizeof(bf));

이렇게 하면 커널은 기존에 bind로 할당된 소켓자원을 프로세스가 재 사용할 수 있도록 허락한다.

[링크 : https://www.joinc.co.kr/w/Site/Network_Programing/AdvancedComm/SocketOption]

 

+

2023.08.01

int      option;

server_socket = socket( PF_INET, SOCK_STREAM, 0);

option = 1;          // SO_REUSEADDR 의 옵션 값을 TRUE 로
setsockopt( server_socket, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option) );

[링크 : https://m.blog.naver.com/cache798/130080237440]

 

프로토 타입은 아래와 같은데 SO_REUSEADDR 은 optname으로 level이 SOL_SOCKET 이라..

optval에는 또 어떻게 넣어줘야 하려나

       #include <sys/types.h>          /* See NOTES */
       #include <sys/socket.h>

       int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);
       int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);

[링크 : https://linux.die.net/man/2/setsockopt]

'Linux API > network' 카테고리의 다른 글

recv 와 read 차이  (0) 2023.06.23
AF_PACKET로 link layer 열기  (0) 2022.06.09
linux tcp server listen accept connect  (0) 2022.05.11
ssl socket 예제  (0) 2022.03.25
TCP timeout  (0) 2020.09.29
Posted by 구차니
Linux API/network2023. 6. 23. 15:40

flag 안쓰면(NULL) 둘 다 거의 동일하다 라고 보면 될 듯.

       The  only  difference  between  recv()  and  read(2) is the presence of
       flags.  With a zero flags argument, recv() is generally  equivalent  to
       read(2) (but see NOTES).  Also, the following call

           recv(sockfd, buf, len, flags);

       is equivalent to

           recvfrom(sockfd, buf, len, flags, NULL, NULL);

NOTES
       If  a  zero-length datagram is pending, read(2) and recv() with a flags
       argument of zero provide different  behavior.   In  this  circumstance,
       read(2) has no effect (the datagram remains pending), while recv() con‐
       sumes the pending datagram.

       The socklen_t type was invented by POSIX.  See also accept(2).

       According to POSIX.1, the msg_controllen field of the msghdr  structure
       should  be typed as socklen_t, and the msg_iovlen field should be typed
       as int, but glibc currently types both as size_t.

       See recvmmsg(2) for information about a Linux-specific system call that
       can be used to receive multiple datagrams in a single call.

[링크 : https://linux.die.net/man/2/recv]

 

[링크 : https://github.com/get-Pork-Belly/Webserv/issues/18]

'Linux API > network' 카테고리의 다른 글

bind(): Address already in use  (0) 2023.07.21
AF_PACKET로 link layer 열기  (0) 2022.06.09
linux tcp server listen accept connect  (0) 2022.05.11
ssl socket 예제  (0) 2022.03.25
TCP timeout  (0) 2020.09.29
Posted by 구차니
Linux API/linux2023. 6. 21. 10:37

파일 이벤트를 감시하는 API

 

그런데 내용만 봐서는 디렉토리 레벨로는 어떻게 감시가 되는데

파일시스템 오류로 파티션 전체가 read only로 바뀌면

해당 이벤트가 모니터링 되는진 좀 더 봐야 할 듯.

[링크 : https://man7.org/linux/man-pages/man7/inotify.7.html]

[링크 : https://sonseungha.tistory.com/436]

[링크 : https://dataonair.or.kr/db-tech-reference/d-lounge/technical-data/?mod=document&uid=236732]

'Linux API > linux' 카테고리의 다른 글

/proc/pid/statm  (0) 2023.10.23
malloc() 으로 할당된 메모리 리스트?  (0) 2023.10.19
system v shmget size  (0) 2023.01.09
segfault시 calltree 출력하기  (0) 2022.11.28
pthread 테스트  (0) 2022.11.24
Posted by 구차니
Linux API/linux2023. 1. 9. 19:05

ipcs -m 하면 키, id, size가 나오는데

어떻게 size를 받아내나 싶어서 찾아보니 먼가 나오긴 한다.

 

struct shmid_ds buf;
shmctl(shm, IPC_STAT, &buf);
int length = (int) buf.shm_segsz / sizeof(int);

[링크 : http:// https://stackoverflow.com/questions/60219469/find-size-of-shared-memory-in-c-shmget]

'Linux API > linux' 카테고리의 다른 글

malloc() 으로 할당된 메모리 리스트?  (0) 2023.10.19
inotify  (0) 2023.06.21
segfault시 calltree 출력하기  (0) 2022.11.28
pthread 테스트  (0) 2022.11.24
pthread  (0) 2022.11.23
Posted by 구차니
Linux API/linux2022. 11. 28. 21:29

arm64(i.mx8) 에서는 

caller_address = (void *) uc->uc_mcontext.arm_pc;

대신

caller_address = (void *) uc->uc_mcontext.pc; 로 하니 빌드가 된다.

 

[링크 : https://snowdeer.github.io/c++/2017/08/30/segmentation-fault-call-stack/]

'Linux API > linux' 카테고리의 다른 글

inotify  (0) 2023.06.21
system v shmget size  (0) 2023.01.09
pthread 테스트  (0) 2022.11.24
pthread  (0) 2022.11.23
iio(industrial io) 문서  (0) 2022.11.11
Posted by 구차니
Linux API/linux2022. 11. 24. 10:23

심심(?)해서 pthread를 1회성으로 구동하고 죽게 냅두면 어떻게 되나 궁금해서 해봤는데

메모리 16GB 시스템에서 32753개 정도까지 밖에 구동 못하고 메모리를 할당할 수 없다고 죽는다.

user space 메모리는 문제가 없는 것 같은데 커널 메모리를 다 먹어 버린건가?

$ cat main.c
#include <stdio.h>
#include <pthread.h>

void *func(int *val)
{
        printf("hello %d\n", *val);
}

void main()
{
        pthread_t pt;
        int pid = 0;
        int i = 0;
        for(i = 0; i < 100000; i++)
        {
                pid = pthread_create(&pt, NULL, func, &i);
                if (pid > 0 )
                {
                        perror("thread create error");
                        exit(0);
                }
        }
}
$ gcc main.c -lpthread
$ ./a.out
hello 32753
thread create error: Cannot allocate memory
$ top
top - 10:16:37 up 8 days, 23:07,  3 users,  load average: 0.39, 0.24, 0.09
Tasks: 363 total,   3 running, 293 sleeping,   0 stopped,   0 zombie
%Cpu(s):  6.2 us, 25.0 sy,  0.0 ni, 66.2 id,  0.0 wa,  0.0 hi,  2.5 si,  0.0 st
KiB Mem : 16169232 total,   808336 free,  2131900 used, 13228996 buff/cache
KiB Swap:  2097148 total,  2095356 free,     1792 used. 13436824 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
25250 minimonk   20   0  0.107t 117784   1584 R 131.8  0.7   0:00.29 a.out
22599 minimonk   20   0  110440   6228   4996 R  81.8  0.0   0:17.60 sshd
21729 root      20   0       0      0      0 I   9.1  0.0   0:00.11 kworker/u16:3-e
22764 root      20   0       0      0      0 I   9.1  0.0   0:01.27 kworker/u16:2-e
17413 root      20   0       0      0      0 I   4.5  0.0   0:02.40 kworker/4:0-eve
18086 root      20   0       0      0      0 I   4.5  0.0   0:02.63 kworker/5:0-eve
21979 root      20   0       0      0      0 I   4.5  0.0   0:01.56 kworker/1:1-eve
22094 root      20   0       0      0      0 I   4.5  0.0   0:00.80 kworker/3:1-eve
22446 root      20   0       0      0      0 I   4.5  0.0   0:00.61 kworker/2:0-eve
27802 minimonk   20   0   45652   4232   3476 R   4.5  0.0   0:00.97 top

[링크 : https://www.joinc.co.kr/w/Site/system_programing/Book_LSP/ch07_Thread]

 

 

+

pthread_join()으로 쓰레드가 끝나길 기다리는데 안 끝난다.

return이 없어서인가.. 쓰레드도 종료를 하는 다른 함수가 있는건가?

 

+

다시 해보니 pthread_join에 포인터로 pthread_t 변수를 넘겨서 그랬던 듯. 잘 돈다.

#include <stdio.h>
#include <pthread.h>

void *func(int *val)
{
    printf("hello %d\n", *val);

//  return ((void*)0);
}

void main()
{
    pthread_t pt;
    int pid = 0;
    int i = 0;
    int status = 0;
    for(i = 0; i < 100000; i++)
    {
        pid = pthread_create(&pt, NULL, func, &i);
        if (pid > 0 )
        {
            perror("thread create error");
            exit(0);
        }
        pthread_join(pt, (void**)&status);
    }
}

[링크 : https://www.joinc.co.kr/w/Site/Thread/Advanced/ThreadCancle]

 

좀.. 비슷한 타입으로 하게 하라고 -_-

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
int pthread_join(pthread_t thread, void **retval);

 

+

pthread_join 안하니 다시 메모리 할당 오류. 쓰레드 에서 return 0 하는거랑은 상관없다.

#include <stdio.h>
#include <pthread.h>

void *func(int *val)
{
        printf("hello %d\n", *val);

//      return ((void*)0);
}

void main()
{
        pthread_t pt;
        int pid = 0;
        int i = 0;
        int status = 0;
        for(i = 0; i < 100000; i++)
        {
                pid = pthread_create(&pt, NULL, func, &i);
                if (pid > 0 )
                {
                        perror("thread create error");
                        exit(0);
                }
//              pthread_join(pt, (void**)&status);
        }
}

 

detach 하면 종료시 자동으로 자원 반납이 된다고 한다.

테스트 해보니 return도 필요없이 쓰레드에서 실행될 함수가 종료되면 그냥 종료된다.

랜덤하게 안되긴 한데, printf가 중첩되서 버퍼가 쌓이며 문제가 생기는거 같기도 하고? (쓰레드를 5만개 넘기는 시점이니)

기본적으로 스레드의 종료 코드는 스레드가 종료되더라도 pthread_join이 호출될 때까지 유지됩니다. 하지만, detatch 상태의 스레드는 종료되는 즉시 자원이 회수됩니다

[링크 : http://xucxo.blogspot.com/2011/03/linux-programming-thread.html]

 

'Linux API > linux' 카테고리의 다른 글

system v shmget size  (0) 2023.01.09
segfault시 calltree 출력하기  (0) 2022.11.28
pthread  (0) 2022.11.23
iio(industrial io) 문서  (0) 2022.11.11
mkpipe 와 poll  (0) 2022.10.26
Posted by 구차니
Linux API/linux2022. 11. 23. 19:03

'Linux API > linux' 카테고리의 다른 글

segfault시 calltree 출력하기  (0) 2022.11.28
pthread 테스트  (0) 2022.11.24
iio(industrial io) 문서  (0) 2022.11.11
mkpipe 와 poll  (0) 2022.10.26
‘F_SETPIPE_SZ’ undeclared  (0) 2022.10.20
Posted by 구차니
Linux API/linux2022. 11. 11. 16:40

내용상 같은 문서 같은데..

왜 kernel.org 문서는 눈에 잘 안들어 올까?

오히려 과도한(?) 서식이 문제인가

 

[링크 : https://www.kernel.org/doc/html/v4.11/driver-api/iio/index.html]

[링크 : https://dbaluta.github.io/index.html]

'Linux API > linux' 카테고리의 다른 글

pthread 테스트  (0) 2022.11.24
pthread  (0) 2022.11.23
mkpipe 와 poll  (0) 2022.10.26
‘F_SETPIPE_SZ’ undeclared  (0) 2022.10.20
linux fifo  (0) 2022.10.18
Posted by 구차니
Linux API/linux2022. 10. 26. 14:24

가능은 한 것 같은데..

[링크 : https://stackoverflow.com/questions/15055065/o-rdwr-on-named-pipes-with-poll]

[링크 : https://man7.org/linux/man-pages/man3/mkfifo.3.html]

 

Macro: int ENXIO“No such device or address.” The system tried to use the device represented by a file you specified, and it couldn’t find the device. This can mean that the device file was installed incorrectly, or that the physical device is missing or not correctly attached to the computer.

[링크 : https://www.gnu.org/software/libc/manual/html_node/Error-Codes.html]

 

+

2022.10.27

POLLIN으로 탐지가 되는 듯?

$ cat rx.c
//#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/poll.h>

#define  FIFO_FILE   "/tmp/fifo"
#define  BUFF_SIZE  1024*768*4
struct pollfd pfd[1];

int main(int argc, char** argv)
{
                int ret = 0;
                int   counter = 0;
                int   fd;
                char  buff[BUFF_SIZE];

                //              printf("argc[%d]\n",argc);
                if ( -1 == mkfifo( FIFO_FILE, 0666)){
                                perror( "mkfifo() 실행에러");
                                exit( 1);
                }

                if ( -1 == ( fd = open( FIFO_FILE, O_RDONLY|O_NONBLOCK))){  //  <---- (A)
                                perror( "open() 실행에러");
                                exit( 1);
                }
                ret = fcntl(fd, F_SETPIPE_SZ, 1024 * 1024);
                pfd[0].fd = fd;
                pfd[0].events = POLLIN;

                printf("fd[%d]ret[%d]\n",fd,ret);

                while( 1 ){
                                int n = poll(pfd, 1, 10);
                                if (n > 0)
                                {
                                        memset( buff, 0, BUFF_SIZE);
                                        ret = read( fd, buff, BUFF_SIZE);
                                        if(ret > 0 )
                                                        printf("ret[%d]\n",ret);
                                        //      printf( "%d: %s\n", counter++, buff);
                                }
                                printf(".");
                                usleep(10000);
                }
                close( fd);
}
$ cat tx.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#define  FIFO_FILE   "/tmp/fifo"

int main_loop = 1;
int write_loop = 1;

void sigint_handler(int sig)
{
                main_loop = 0;
                write_loop = 0;
}

void sigpipe_handler(int sig)
{
                write_loop = 0;
}

int main(int argc, char **argv)
{
                int   fd;
                int   fd_r;
                //   char *str   = "badayak.com";
                char *str = NULL;
                char *temp = NULL;

                str = (char*)malloc(1024*768*4);
                temp = (char*)malloc(1024*768*4);
                memset(str, *argv[1], 1024*768*4);

//              signal(SIGPIPE, SIG_IGN);
                signal(SIGPIPE, &sigpipe_handler);
                signal(SIGINT, &sigint_handler);
                /*
                   printf("%d\n",__LINE__);
                   if ( -1 == mkfifo( FIFO_FILE, 0666)){
                   perror( "mkfifo() 실행에러");
                   exit( 1);
                   }
                 */
                while(main_loop)
                {
                                printf("%d\n",__LINE__);
                                do {
                                                fd = open( FIFO_FILE, O_WRONLY | O_NONBLOCK);
                                                usleep(100000);
                                                printf("fd[%d] %d\n",fd,__LINE__);
                                                if(main_loop == 0 && write_loop == 0) exit(1);
                                } while(fd == -1);
                                write_loop = 1;

                                int ret = 0;
                                while(write_loop)
                                {
                                                printf("%d\n",__LINE__);
                                                int a = write( fd, str, atoi(argv[1]));
                                                printf("%d a[%d]\n",__LINE__,a);
                                                usleep(1000000);
                                }
                }
                close( fd);
}

'Linux API > linux' 카테고리의 다른 글

pthread  (0) 2022.11.23
iio(industrial io) 문서  (0) 2022.11.11
‘F_SETPIPE_SZ’ undeclared  (0) 2022.10.20
linux fifo  (0) 2022.10.18
SIGPIPE  (0) 2022.10.17
Posted by 구차니