<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Linux Forum &mdash; Сигналы с дополнительной информацией в с]]></title>
		<link>https://linuxforum.ru/viewtopic.php?id=32898</link>
		<atom:link href="https://linuxforum.ru/extern.php?action=feed&amp;tid=32898&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «Сигналы с дополнительной информацией в с».]]></description>
		<lastBuildDate>Wed, 08 Jan 2014 05:48:17 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Re: Сигналы с дополнительной информацией в с]]></title>
			<link>https://linuxforum.ru/viewtopic.php?pid=386088#p386088</link>
			<description><![CDATA[<div class="quotebox"><cite>Fat-Zer пишет:</cite><blockquote><p>Собственно зачем это всё?</p></blockquote></div><p>Спортивный интерес.</p><p>Рабочий код<br /></p><div class="codebox"><pre><code>#include &lt;stdio.h&gt;
#include &lt;unistd.h&gt;
#include &lt;sys/epoll.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;sys/ioctl.h&gt;
#include &lt;openssl/md5.h&gt;
#include &lt;stdint.h&gt;
#include &lt;stdbool.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;stdint.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;pthread.h&gt;
#include &lt;postgresql/libpq-fe.h&gt;
#include &lt;signal.h&gt;

void hello (int signum, siginfo_t *info, void *f)
{
  fprintf (stderr, &quot;привет от %i\n&quot;, info-&gt;si_fd);
}

int main ()
{
  struct sigaction act;
  memset (&amp;act, 0, sizeof(act));
 
  act.sa_sigaction = hello;
  act.sa_flags = SA_SIGINFO;
  sigaction (SIGUSR1, &amp;act, NULL);

  int client = 0;
  struct sockaddr_in saddr;
  int sd = socket (AF_INET, SOCK_STREAM, 0);

  memset(&amp;saddr, 0, sizeof(struct sockaddr_in));
  saddr.sin_family = AF_INET;
  saddr.sin_addr.s_addr = INADDR_ANY;
  saddr.sin_port = htons(4000);

  if (bind(sd, (struct sockaddr *)&amp;saddr, sizeof(struct sockaddr_in)) &lt; 0 ) {
    perror (&quot;bind&quot;);
    close (sd);
    return 1;
  }
 
  while (1) {

    int size = sizeof (saddr);
    memset (&amp;saddr, 0, size);

    client = accept (sd, (struct sockaddr *)&amp;saddr, &amp;size);
    if (client &gt; 0)  {
      int s_f;
      fcntl(client, F_SETOWN, getpid());
      fcntl(client, F_SETFL, FASYNC);
      fcntl(client, F_SETSIG, SIGUSR1);
 
    }
    else {
      perror (&quot;Ошибка обработки входящего сокета&quot;);
      continue;
    }
  }
}</code></pre></div><p>Компиляция<br /></p><div class="codebox"><pre><code> gcc test.c -D_GNU_SOURCE </code></pre></div>]]></description>
			<author><![CDATA[null@example.com (marikk)]]></author>
			<pubDate>Wed, 08 Jan 2014 05:48:17 +0000</pubDate>
			<guid>https://linuxforum.ru/viewtopic.php?pid=386088#p386088</guid>
		</item>
		<item>
			<title><![CDATA[Re: Сигналы с дополнительной информацией в с]]></title>
			<link>https://linuxforum.ru/viewtopic.php?pid=385491#p385491</link>
			<description><![CDATA[<div class="quotebox"><cite>marikk пишет:</cite><blockquote><p>Так же не получается установить посылаемый сигнал с помощью  fcntl, F_SETSIG. Выдает ошибку (F_SETSIG undeclared (first use in this function)).</p></blockquote></div><p>компилируй с <strong>-D_GNU_SOURCE</strong><br />или задефайнь его до первого инклюда.</p><div class="quotebox"><cite>marikk пишет:</cite><blockquote><p>Сигнал успешно принимается распознается, но вот номер сокета выводится некорректно 205760316 или -588753092.</p></blockquote></div><p>скорее всего это из-за отсутствия вызова fcntl().</p><p>Собственно зачем это всё? есть же poll/select.</p>]]></description>
			<author><![CDATA[null@example.com (Fat-Zer)]]></author>
			<pubDate>Thu, 02 Jan 2014 06:03:47 +0000</pubDate>
			<guid>https://linuxforum.ru/viewtopic.php?pid=385491#p385491</guid>
		</item>
		<item>
			<title><![CDATA[Сигналы с дополнительной информацией в с]]></title>
			<link>https://linuxforum.ru/viewtopic.php?pid=384448#p384448</link>
			<description><![CDATA[<p>Всем привет. Помогите пожалуйста получить сигнал от сокета с дополнительной информацией.<br />Информация из man fcntl:<br /></p><div class="fancy_spoiler_switcher"><div class="fancy_spoiler_switcher_header" data-lang-open="открыть спойлер" data-lang-close="скрыть спойлер"><strong>+</strong>&nbsp;открыть спойлер</div><div class="fancy_spoiler"><p>F_SETSIG (int)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Set&nbsp; the&nbsp; signal&nbsp; sent&nbsp; when input or output becomes possible to the value given in arg.&nbsp; A value of zero means to send the default SIGIO<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; signal.&nbsp; Any other value (including SIGIO) is the signal to send instead, and in this case additional info is&nbsp; available&nbsp; to&nbsp; the&nbsp; signal<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler if installed with SA_SIGINFO.</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; By&nbsp; using&nbsp; F_SETSIG&nbsp; with&nbsp; a nonzero value, and setting SA_SIGINFO for the signal handler (see sigaction(2)), extra information about I/O<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; events is passed to the handler in a siginfo_t structure.&nbsp; If the si_code field indicates the source is SI_SIGIO, the si_fd&nbsp; field&nbsp; gives<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; the&nbsp; file descriptor associated with the event.&nbsp; Otherwise, there is no indication which file descriptors are pending, and you should use<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; the usual mechanisms (select(2), poll(2), read(2) with O_NONBLOCK set etc.) to determine which file descriptors are available for I/O.</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; By selecting a real time signal (value &gt;= SIGRTMIN), multiple I/O events may be queued using the same signal numbers.&nbsp; (Queuing is depen‐<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dent on available memory).&nbsp; Extra information is available if SA_SIGINFO is set for the signal handler, as above.</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Note&nbsp; that&nbsp; Linux imposes a limit on the number of real-time signals that may be queued to a process (see getrlimit(2) and signal(7)) and<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if this limit is reached, then the kernel reverts to delivering SIGIO, and this signal is delivered to the entire process rather than&nbsp; to<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a specific thread.</p></div></div><p>На русском<br /></p><div class="fancy_spoiler_switcher"><div class="fancy_spoiler_switcher_header" data-lang-open="открыть спойлер" data-lang-close="скрыть спойлер"><strong>+</strong>&nbsp;открыть спойлер</div><div class="fancy_spoiler"><p>F_SETSIG<br />Установить сигнал, который будет послан, когда станет возможен ввод или вывол. Значение 0 означает сигнал SIGIO. Любое другое значение (включая SIGIO) является другим сигналам, посылаемым вместо SIGIO и в это случае, для обработчика сигнала доступна дополнительная информация, если он был установлен с SA_SIGINFO.<br />В случае использования F_SETSIG с ненулевым значением и установкой SA_SIGINFO для обработчика сигнала (см. sigaction(2)), обработчику передаётся дополнительная информация о событиях ввода/вывода в структуре siginfo_t. Если поле si_code показывает, что сигналом является SI_SIGIO, то поле si_fd содержит файловый дескриптор, ассоциированный с собрытием вывода/вывода. В противном случае, не существует никакого механизма, чтобы сообщить с каким файловым дескриптором связан полученный сигнал и вы должны использовать (select(2), poll(2), read(2) с установленным флагом O_NONBLOCK и т.д.) чтобы определить какой файловый дескриптор доступен для ввода/вывода.</p><p>При выборе сигнала реального времени (value &gt;= SIGRTMIN) как описано в POSIX.1b, в очередь будут добавляться несколько событий ввода вывода, с теми же номерами сигналов. (Размер очереди зависит от доступной памяти). Дополнительная информация будет доступна как описано выше, если для обработчика сигнала будет установлено SA_SIGINFO.</p></div></div><p>Мои попытки<br /></p><div class="codebox"><pre><code>#include &lt;unistd.h&gt;
#include &lt;fcntl.h&gt;
#include &lt;sys/ioctl.h&gt;
#include &lt;stdint.h&gt;
#include &lt;stdbool.h&gt;
#include &lt;stdint.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;signal.h&gt;

void hello (int signum, siginfo_t *info, void *f)
{
  if (info-&gt;si_signo == SIGIO)
    fprintf (stderr, &quot;Сигнал получен от %i  \n&quot;, info-&gt;si_fd);
}

int main ()
{
  struct sigaction act;
  memset (&amp;act, 0, sizeof(act));

  act.sa_sigaction = hello;
  act.sa_flags = SA_SIGINFO;
  sigaction (SIGIO, &amp;act, NULL);

 int client = 0;
  struct sockaddr_in saddr;
  int sd = socket (AF_INET, SOCK_STREAM, 0);

  memset(&amp;saddr, 0, sizeof(struct sockaddr_in));
  saddr.sin_family = AF_INET;
  saddr.sin_addr.s_addr = INADDR_ANY;
  saddr.sin_port = htons(4000);

  if (bind(sd, (struct sockaddr *)&amp;saddr, sizeof(struct sockaddr_in)) &lt; 0 ) {
    perror (&quot;bind&quot;);
    close (sd);
    return 1;
  }

  if ( listen(sd, 20) != 0) {
    perror (&quot;Listen&quot;);
    close (sd);
    return 1;
  }

  while (1) {
    int size = sizeof (saddr);
    memset (&amp;saddr, 0, size);

    client = accept (sd, (struct sockaddr *)&amp;saddr, &amp;size);
    if (client &gt; 0)  {
      int s_f;
      fcntl(client, F_SETOWN, getpid());
      fcntl(client, F_SETFL, FASYNC);
    }
    else { 
      perror (&quot;Ошибка обработки входящего сокета&quot;);
      continue;
    }
  }
} </code></pre></div><p>После коннекта отправляю порцию данных. Сигнал успешно принимается распознается, но вот номер сокета выводится некорректно 205760316 или -588753092.<br />Так же не получается установить посылаемый сигнал с помощью&nbsp; fcntl, F_SETSIG. Выдает ошибку (F_SETSIG undeclared (first use in this function)).<br />uname -a<br /></p><div class="quotebox"><blockquote><p>Linux vmovs-admin 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:31:23 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux</p></blockquote></div>]]></description>
			<author><![CDATA[null@example.com (marikk)]]></author>
			<pubDate>Thu, 26 Dec 2013 07:52:11 +0000</pubDate>
			<guid>https://linuxforum.ru/viewtopic.php?pid=384448#p384448</guid>
		</item>
	</channel>
</rss>
