Linux find socket files

I’m doing debugging for a program that uses UDP socket. The program creates a socket but after that due to some other problems the program gets stuck and I cannot kill it properly. So I close the command shell and the process goes into ‘defunct’ state. I guess the socket has not been released in this process because next time I run the program, during the socket creation, it says ‘create : Address already in use’. Of course I can start the experiment again if I reboot the computer (actually a small board, with ubuntu 16.04 installed).
I know everything in linux is file, so there should be the socket file somewhere. and I have read here (https://stackoverflow.com/questions/34873151/how-can-i-delete-a-unix-domain-socket-file-when-i-exit-my-application) that I can unlink the socket(using command unlink ) and remove it. Where can I find the socket file and how can I get information about the socket file(after I find it)?

2 Answers 2

Have a Google for the UDP (and TCP) socket parameter called «REUSEADDR» (or «SO_REUSEADDR» etc.) as well as REUSEPORT (to see the difference).

If you use «REUSEADDR» when you create the UDP socket in your app, then SO_REUSEADDR flag will be set when binding to the port. This means that multiple threads or processes can bind to the same address:port without error (provided they all set the flag). Note that only the last process to bind will receive traffic, taking control from the previous listener (in your case, the dead app).

When designing server apps, it is good practice to set the REUSEADDR flag, to allow for fast restarts of the service, else you sit waiting for the bind to succeed. This will allow you to restart your app, without having to hack the socket files, which should be left to the system to manage.

I think lsof -iUDP is what you’re looking for:

$ sudo lsof -iUDP COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME avahi-dae 726 avahi 12u IPv4 21843 0t0 UDP *:mdns avahi-dae 726 avahi 13u IPv6 21844 0t0 UDP *:mdns avahi-dae 726 avahi 14u IPv4 21845 0t0 UDP *:46374 avahi-dae 726 avahi 15u IPv6 21846 0t0 UDP *:34483 NetworkMa 732 root 23u IPv4 32835 0t0 UDP stewbian:bootpc->_gateway:bootps postgres 848 postgres 8u IPv6 21908 0t0 UDP localhost:58947->localhost:58947 postgres 849 postgres 8u IPv6 21916 0t0 UDP localhost:35817->localhost:35817 postgres 850 postgres 8u IPv6 21912 0t0 UDP localhost:40321->localhost:40321 postgres 858 postgres 8u IPv6 21908 0t0 UDP localhost:58947->localhost:58947 postgres 859 postgres 8u IPv6 21908 0t0 UDP localhost:58947->localhost:58947 postgres 860 postgres 8u IPv6 21908 0t0 UDP localhost:58947->localhost:58947 postgres 861 postgres 8u IPv6 21908 0t0 UDP localhost:58947->localhost:58947 postgres 865 postgres 8u IPv6 21912 0t0 UDP localhost:40321->localhost:40321 0t0 UDP localhost:35817->localhost:35817 postgres 877 postgres 8u IPv6 21916 0t0 UDP localhost:35817->localhost:35817 cups-brow 5729 root 7u IPv4 153431 0t0 UDP *:631 

You can see you have the PID and the process name. I suspect that is enough to kill $PID to unbind the address.

Читайте также:  Чем открыть ini linux

Hi, thanks. (but I couldn’t find the culprit socket with this method. I even tried the Zombie process, but it still gives me Adderss already in use’ message.

Источник

Команда find в linux — описание, опции, примеры

Справка по команде find в Linux для поиска файлов и каталогов.

Примеры поиска

find . -type f -name '*.php' -maxdepth 3 -exec grep 'video-search' <> + ## поиск по названию и содержимому find ~/ -maxdepth 7 -type f -not -path '*/.*' -not -path '*/node_modules*' -name *.txt ## поиск txt файлов по названию 
find [-H -L -P] [-Oуровень] [-D help|tree|search|stat|rates|opt|exec] [путь. ] [выражение]

Опции

find ./ -print0 Вывести пути к файлам и символ «NULL» в качестве разделителя. find ./ -printf '' Форматировать вывод. find ./ -type '' 
%p /home/user/Рабочий стол/file.txt Путь к файлу %h /home/user/Рабочий стол/ Каталог файла %f file.txt Имя файла %c Mon Jan 13 16:13:53.8401175430 2020 Дата модификации %C@ 1578928478.3940218700 секунды.наносекунды с начала эпохи линукс %Cs 1578928478 секунды с начала эпохи (since 1970-01-01 00:00 GMT) ## Формат опций из команды date: %TF 2020-01-13 Дата модификации %TT 16:13:54.0081247250 Время модификации (добавляет nanoseconds) %TY-%Tm-%Td %TH:%TM:%TS Время создания/модификации файла. Аналог: %CY-%Cm-%Cd %CH:%CM:%CS %g root Группа владельца %G 1000 ID группы владельца %u root Имя пользователя/владельца %U 1000 ID пользователя/владельца %m 600 Биты прав доступа %#m 0600 Биты прав доступа с ведущим "0" %M -rw------- Права доступа в символьной записи ## @see https://www.gnu.org/software/findutils/manual/html_mono/find.html#Location-Directives
Примечание

Если имена файлов могут содержать пробелы — нужно указывать опцию -print0:

find ./ -print0 выводить полные имена файлов и символ «NULL» в качестве разделителя xargs -0 задать символ "NULL" в качестве разделителя. По умолчанию "пробел" или "перенос строки"

По типу

find ./ -type f # Файлы. Типы файлов: f - файл, d - directory, l - link, p - pipe/канал, s - socket find ./ -type d # Каталоги

По названию

Поиск файла по маске содержимого (regex):

Читайте также:  Windows 10 установка linux subsystem

Формат вывода

find ./ -type f -printf '"%p" %Cs\n' # Вывести полный путь и timestamp модификации 

По времени/дате

Время обращения/модификации файла в минутах:

find ./ -amin -30 # время последнего обращения менее 30 мин назад (access time) find ./ -cmin -30 # время последнего изменения мета-данных менее 30 мин назад find ./ -mmin -30 # время последней модификации/создания файла менее 30 мин назад 

Время последнего обращения/модификации файла в днях:

find ./ -atime +2 # время последнего обращения к файлу более 2 дней find ./ -ctime +2 # время последнего изменения владельца или прав доступа в днях find ./ -mtime +2 # время последнего изменения/создания файла более 2 дней 
find ./ -newermt "2019-10-13 06:47" # время изменения/создания файла больше указанной даты find ./ ! -newermt '2021-05-27 10:00:00' -print0 find ./ -newerat 2019-10-13 # время обращения к файлу больше указанной даты 

Новее даты указанного файла:

find ./ -newer /tmp/sync_timestamp # время изменения/создания файла больше чем дата модификации указанного файла

По размеру

find ./ -size +100к -size -50M # больше 100 Кбайт но меньше 50 Мбайт find ./ -size -900c # меньше 900 байт

Команды

Примеры команд/операций над найденными файлами:

find some-dir/ -type f -print0 | xargs -0 echo ## Простой пример конвейерной обработки после find find some-dir/ -type f -print0 | xargs -0 mv -t some-dir/dir ## Переместить только файлы в каталог find ./some-dir/ -name 'file-mask-*.txt' -exec rm -rf '<>' \ ## Удалить файлы find ./some-dir/ -name 'file-mask-*.txt' -exec chown www-data <> \; ## Изменить владельца файлов 

#find #grep #поиск файлов в linux

Источник

How do I find the file name associated with a socket descriptor?

When I want to see the list of open files for a process using ls -l /proc/pid/fd , I see some socket descriptors. How can I find the respective file names?

lr-x------ 1 u1 users 64 Sep 15 14:45 0 -> /dev/null lrwx------ 1 u1 users 64 Sep 15 14:45 1 -> /dev/pts/3 lrwx------ 1 u1 users 64 Sep 15 14:45 10 -> socket:[507942] l-wx------ 1 u1 users 64 Sep 15 14:45 2 -> pipe:[505993] l-wx------ 1 u1 users 64 Sep 15 14:45 22 -> pipe:[505994] l-wx------ 1 u1 users 64 Sep 15 14:45 3 -> /dev/null lrwx------ 1 u1 users 64 Sep 15 14:45 4 -> socket:[507938] lrwx------ 1 u1 users 64 Sep 15 14:45 5 -> socket:[507939] lrwx------ 1 u1 users 64 Sep 15 14:45 6 -> socket:[486323] lrwx------ 1 u1 users 64 Sep 15 14:45 7 -> socket:[486324] lrwx------ 1 u1 users 64 Sep 15 14:45 8 -> socket:[509999] lrwx------ 1 u1 users 64 Sep 15 14:45 9 -> socket:[507941] 
atIcoFoam 24376 u1 0r CHR 1,3 0t0 1029 /dev/null atIcoFoam 24376 u1 1u CHR 136,3 0t0 6 /dev/pts/3 atIcoFoam 24376 u1 2w FIFO 0,8 0t0 506122 pipe atIcoFoam 24376 u1 3w CHR 1,3 0t0 1029 /dev/null atIcoFoam 24376 u1 4u unix 0x0000000000000000 0t0 511127 socket atIcoFoam 24376 u1 5u unix 0x0000000000000000 0t0 511128 socket atIcoFoam 24376 u1 6u IPv4 510153 0t0 TCP *:37340 (LISTEN) atIcoFoam 24376 u1 7u IPv6 510154 0t0 TCP *:43305 (LISTEN) atIcoFoam 24376 u1 8u IPv4 512654 0t0 TCP hpclab.ws05:57696->hpclab.ws05:33141 (ESTABLISHED) atIcoFoam 24376 u1 9u IPv4 508030 0t0 TCP *:1027 (LISTEN) atIcoFoam 24376 u1 10u IPv6 508031 0t0 TCP *:1027 (LISTEN) 

Источник

Читайте также:  Планшет на linux arm

How do I find out more about socket files in /proc/fd?

Because I have access to the code, I know these sockets are tied to TCP connections (one is a connection to port 5672 on some machine, another is a connection to port 3306 on some other machine), but I want to know which socket is tied to which connection. How can I do that? More generally, how can I ask the OS what is at the other end of the socket?

1 Answer 1

Command lsof

A good option might be lsof . As man lsof states it is handy for obtaining information about open files such as Internet sockets or Unix Domain sockets .

Using it

At first, get an overview about /proc/$PID/fd/ and the listed socket numbers.
For example, socket:[14240] might interest you.

Then use lsof -i -a -p $PID to print a list of all network files $PID uses.

  • -i produces a list of network files belonging to a user or process
  • -a logically combines or AND’s given parameters
  • -p $PID selects info only about your process

A typical output for my browser running with a PID of 2543 might be:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME browser 2543 pidi 55u IPv4 14240 0t0 TCP pidi.router.lan:55038->stackoverflow.com:https (ESTABLISHED) 

Great! Now take a closer look at the DEVICE column. It matches our previously listed socket from /proc/$PID/fd/ !
And thanks to the NAME section we can say what the other end of our socket is.

In a real world run you might get a good amount of output, but just filter or grep for your socket of interest.

I’m pretty sure one could combine all commands, but that should be enough to get you started.

Источник

Оцените статью
Adblock
detector