Simplify last change.
[bpt/emacs.git] / src / process.c
1 /* Asynchronous subprocess control for GNU Emacs.
2 Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994, 1995,
3 1996, 1998, 1999, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 #include <config.h>
23 #include <signal.h>
24
25 /* This file is split into two parts by the following preprocessor
26 conditional. The 'then' clause contains all of the support for
27 asynchronous subprocesses. The 'else' clause contains stub
28 versions of some of the asynchronous subprocess routines that are
29 often called elsewhere in Emacs, so we don't have to #ifdef the
30 sections that call them. */
31
32 \f
33 #ifdef subprocesses
34
35 #include <stdio.h>
36 #include <errno.h>
37 #include <setjmp.h>
38 #include <sys/types.h> /* some typedefs are used in sys/file.h */
39 #include <sys/file.h>
40 #include <sys/stat.h>
41 #ifdef HAVE_INTTYPES_H
42 #include <inttypes.h>
43 #endif
44 #ifdef STDC_HEADERS
45 #include <stdlib.h>
46 #endif
47
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51 #include <fcntl.h>
52
53 #ifdef HAVE_SOCKETS /* TCP connection support, if kernel can do it */
54 #include <sys/socket.h>
55 #include <netdb.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
58
59 /* Are local (unix) sockets supported? */
60 #if defined (HAVE_SYS_UN_H)
61 #if !defined (AF_LOCAL) && defined (AF_UNIX)
62 #define AF_LOCAL AF_UNIX
63 #endif
64 #ifdef AF_LOCAL
65 #define HAVE_LOCAL_SOCKETS
66 #include <sys/un.h>
67 #endif
68 #endif
69 #endif /* HAVE_SOCKETS */
70
71 #if defined(BSD_SYSTEM)
72 #include <sys/ioctl.h>
73 #if !defined (O_NDELAY) && defined (HAVE_PTYS) && !defined(USG5)
74 #include <fcntl.h>
75 #endif /* HAVE_PTYS and no O_NDELAY */
76 #endif /* BSD_SYSTEM */
77
78 #ifdef NEED_BSDTTY
79 #include <bsdtty.h>
80 #endif
81
82 /* Can we use SIOCGIFCONF and/or SIOCGIFADDR */
83 #ifdef HAVE_SOCKETS
84 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_NET_IF_H)
85 /* sys/ioctl.h may have been included already */
86 #ifndef SIOCGIFADDR
87 #include <sys/ioctl.h>
88 #endif
89 #include <net/if.h>
90 #endif
91 #endif
92
93 #ifdef HAVE_SYS_WAIT
94 #include <sys/wait.h>
95 #endif
96
97 #ifdef HAVE_RES_INIT
98 #include <netinet/in.h>
99 #include <arpa/nameser.h>
100 #include <resolv.h>
101 #endif
102
103 #include "lisp.h"
104 #include "systime.h"
105 #include "systty.h"
106
107 #include "window.h"
108 #include "buffer.h"
109 #include "character.h"
110 #include "coding.h"
111 #include "process.h"
112 #include "frame.h"
113 #include "termhooks.h"
114 #include "termopts.h"
115 #include "commands.h"
116 #include "keyboard.h"
117 #include "blockinput.h"
118 #include "dispextern.h"
119 #include "composite.h"
120 #include "atimer.h"
121
122 Lisp_Object Qprocessp;
123 Lisp_Object Qrun, Qstop, Qsignal;
124 Lisp_Object Qopen, Qclosed, Qconnect, Qfailed, Qlisten;
125 Lisp_Object Qlocal, Qipv4, Qdatagram;
126 Lisp_Object Qreal, Qnetwork, Qserial;
127 #ifdef AF_INET6
128 Lisp_Object Qipv6;
129 #endif
130 Lisp_Object QCport, QCspeed, QCprocess;
131 Lisp_Object QCbytesize, QCstopbits, QCparity, Qodd, Qeven;
132 Lisp_Object QCflowcontrol, Qhw, Qsw, QCsummary;
133 Lisp_Object QCname, QCbuffer, QChost, QCservice, QCtype;
134 Lisp_Object QClocal, QCremote, QCcoding;
135 Lisp_Object QCserver, QCnowait, QCnoquery, QCstop;
136 Lisp_Object QCsentinel, QClog, QCoptions, QCplist;
137 Lisp_Object Qlast_nonmenu_event;
138 /* QCfamily is declared and initialized in xfaces.c,
139 QCfilter in keyboard.c. */
140 extern Lisp_Object QCfamily, QCfilter;
141
142 /* Qexit is declared and initialized in eval.c. */
143
144 /* QCfamily is defined in xfaces.c. */
145 extern Lisp_Object QCfamily;
146 /* QCfilter is defined in keyboard.c. */
147 extern Lisp_Object QCfilter;
148
149 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
150 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
151 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
152 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
153
154 #ifdef HAVE_SOCKETS
155 #define NETCONN_P(p) (EQ (XPROCESS (p)->type, Qnetwork))
156 #define NETCONN1_P(p) (EQ ((p)->type, Qnetwork))
157 #define SERIALCONN_P(p) (EQ (XPROCESS (p)->type, Qserial))
158 #define SERIALCONN1_P(p) (EQ ((p)->type, Qserial))
159 #else
160 #define NETCONN_P(p) 0
161 #define NETCONN1_P(p) 0
162 #define SERIALCONN_P(p) 0
163 #define SERIALCONN1_P(p) 0
164 #endif /* HAVE_SOCKETS */
165
166 /* Define first descriptor number available for subprocesses. */
167 #define FIRST_PROC_DESC 3
168
169 /* Define SIGCHLD as an alias for SIGCLD. There are many conditionals
170 testing SIGCHLD. */
171
172 #if !defined (SIGCHLD) && defined (SIGCLD)
173 #define SIGCHLD SIGCLD
174 #endif /* SIGCLD */
175
176 #include "syssignal.h"
177
178 #include "syswait.h"
179
180 extern char *get_operating_system_release ();
181
182 /* Serial processes require termios or Windows. */
183 #if defined (HAVE_TERMIOS) || defined (WINDOWSNT)
184 #define HAVE_SERIAL
185 #endif
186
187 #ifdef HAVE_SERIAL
188 /* From sysdep.c or w32.c */
189 extern int serial_open (char *port);
190 extern void serial_configure (struct Lisp_Process *p, Lisp_Object contact);
191 #endif
192
193 #ifndef USE_CRT_DLL
194 extern int errno;
195 #endif
196
197 #ifndef HAVE_H_ERRNO
198 extern int h_errno;
199 #endif
200
201 /* t means use pty, nil means use a pipe,
202 maybe other values to come. */
203 static Lisp_Object Vprocess_connection_type;
204
205 /* These next two vars are non-static since sysdep.c uses them in the
206 emulation of `select'. */
207 /* Number of events of change of status of a process. */
208 int process_tick;
209 /* Number of events for which the user or sentinel has been notified. */
210 int update_tick;
211
212 /* Define NON_BLOCKING_CONNECT if we can support non-blocking connects. */
213
214 #ifdef BROKEN_NON_BLOCKING_CONNECT
215 #undef NON_BLOCKING_CONNECT
216 #else
217 #ifndef NON_BLOCKING_CONNECT
218 #ifdef HAVE_SOCKETS
219 #ifdef HAVE_SELECT
220 #if defined (HAVE_GETPEERNAME) || defined (GNU_LINUX)
221 #if defined (O_NONBLOCK) || defined (O_NDELAY)
222 #if defined (EWOULDBLOCK) || defined (EINPROGRESS)
223 #define NON_BLOCKING_CONNECT
224 #endif /* EWOULDBLOCK || EINPROGRESS */
225 #endif /* O_NONBLOCK || O_NDELAY */
226 #endif /* HAVE_GETPEERNAME || GNU_LINUX */
227 #endif /* HAVE_SELECT */
228 #endif /* HAVE_SOCKETS */
229 #endif /* NON_BLOCKING_CONNECT */
230 #endif /* BROKEN_NON_BLOCKING_CONNECT */
231
232 /* Define DATAGRAM_SOCKETS if datagrams can be used safely on
233 this system. We need to read full packets, so we need a
234 "non-destructive" select. So we require either native select,
235 or emulation of select using FIONREAD. */
236
237 #ifdef BROKEN_DATAGRAM_SOCKETS
238 #undef DATAGRAM_SOCKETS
239 #else
240 #ifndef DATAGRAM_SOCKETS
241 #ifdef HAVE_SOCKETS
242 #if defined (HAVE_SELECT) || defined (FIONREAD)
243 #if defined (HAVE_SENDTO) && defined (HAVE_RECVFROM) && defined (EMSGSIZE)
244 #define DATAGRAM_SOCKETS
245 #endif /* HAVE_SENDTO && HAVE_RECVFROM && EMSGSIZE */
246 #endif /* HAVE_SELECT || FIONREAD */
247 #endif /* HAVE_SOCKETS */
248 #endif /* DATAGRAM_SOCKETS */
249 #endif /* BROKEN_DATAGRAM_SOCKETS */
250
251 #if !defined (ADAPTIVE_READ_BUFFERING) && !defined (NO_ADAPTIVE_READ_BUFFERING)
252 #ifdef EMACS_HAS_USECS
253 #define ADAPTIVE_READ_BUFFERING
254 #endif
255 #endif
256
257 #ifdef ADAPTIVE_READ_BUFFERING
258 #define READ_OUTPUT_DELAY_INCREMENT 10000
259 #define READ_OUTPUT_DELAY_MAX (READ_OUTPUT_DELAY_INCREMENT * 5)
260 #define READ_OUTPUT_DELAY_MAX_MAX (READ_OUTPUT_DELAY_INCREMENT * 7)
261
262 /* Number of processes which have a non-zero read_output_delay,
263 and therefore might be delayed for adaptive read buffering. */
264
265 static int process_output_delay_count;
266
267 /* Non-zero if any process has non-nil read_output_skip. */
268
269 static int process_output_skip;
270
271 /* Non-nil means to delay reading process output to improve buffering.
272 A value of t means that delay is reset after each send, any other
273 non-nil value does not reset the delay. A value of nil disables
274 adaptive read buffering completely. */
275 static Lisp_Object Vprocess_adaptive_read_buffering;
276 #else
277 #define process_output_delay_count 0
278 #endif
279
280
281 #include "sysselect.h"
282
283 static int keyboard_bit_set P_ ((SELECT_TYPE *));
284 static void deactivate_process P_ ((Lisp_Object));
285 static void status_notify P_ ((struct Lisp_Process *));
286 static int read_process_output P_ ((Lisp_Object, int));
287
288 /* If we support a window system, turn on the code to poll periodically
289 to detect C-g. It isn't actually used when doing interrupt input. */
290 #ifdef HAVE_WINDOW_SYSTEM
291 #define POLL_FOR_INPUT
292 #endif
293
294 static Lisp_Object get_process ();
295 static void exec_sentinel ();
296
297 extern EMACS_TIME timer_check ();
298 extern int timers_run;
299 \f
300 /* Mask of bits indicating the descriptors that we wait for input on. */
301
302 static SELECT_TYPE input_wait_mask;
303
304 /* Mask that excludes keyboard input descriptor(s). */
305
306 static SELECT_TYPE non_keyboard_wait_mask;
307
308 /* Mask that excludes process input descriptor(s). */
309
310 static SELECT_TYPE non_process_wait_mask;
311
312 /* Mask for the gpm mouse input descriptor. */
313
314 static SELECT_TYPE gpm_wait_mask;
315
316 #ifdef NON_BLOCKING_CONNECT
317 /* Mask of bits indicating the descriptors that we wait for connect to
318 complete on. Once they complete, they are removed from this mask
319 and added to the input_wait_mask and non_keyboard_wait_mask. */
320
321 static SELECT_TYPE connect_wait_mask;
322
323 /* Number of bits set in connect_wait_mask. */
324 static int num_pending_connects;
325
326 #define IF_NON_BLOCKING_CONNECT(s) s
327 #else
328 #define IF_NON_BLOCKING_CONNECT(s)
329 #endif
330
331 /* The largest descriptor currently in use for a process object. */
332 static int max_process_desc;
333
334 /* The largest descriptor currently in use for keyboard input. */
335 static int max_keyboard_desc;
336
337 /* The largest descriptor currently in use for gpm mouse input. */
338 static int max_gpm_desc;
339
340 /* Nonzero means delete a process right away if it exits. */
341 static int delete_exited_processes;
342
343 /* Indexed by descriptor, gives the process (if any) for that descriptor */
344 Lisp_Object chan_process[MAXDESC];
345
346 /* Alist of elements (NAME . PROCESS) */
347 Lisp_Object Vprocess_alist;
348
349 /* Buffered-ahead input char from process, indexed by channel.
350 -1 means empty (no char is buffered).
351 Used on sys V where the only way to tell if there is any
352 output from the process is to read at least one char.
353 Always -1 on systems that support FIONREAD. */
354
355 /* Don't make static; need to access externally. */
356 int proc_buffered_char[MAXDESC];
357
358 /* Table of `struct coding-system' for each process. */
359 static struct coding_system *proc_decode_coding_system[MAXDESC];
360 static struct coding_system *proc_encode_coding_system[MAXDESC];
361
362 #ifdef DATAGRAM_SOCKETS
363 /* Table of `partner address' for datagram sockets. */
364 struct sockaddr_and_len {
365 struct sockaddr *sa;
366 int len;
367 } datagram_address[MAXDESC];
368 #define DATAGRAM_CHAN_P(chan) (datagram_address[chan].sa != 0)
369 #define DATAGRAM_CONN_P(proc) (PROCESSP (proc) && datagram_address[XPROCESS (proc)->infd].sa != 0)
370 #else
371 #define DATAGRAM_CHAN_P(chan) (0)
372 #define DATAGRAM_CONN_P(proc) (0)
373 #endif
374
375 /* Maximum number of bytes to send to a pty without an eof. */
376 static int pty_max_bytes;
377
378 /* Nonzero means don't run process sentinels. This is used
379 when exiting. */
380 int inhibit_sentinels;
381
382 #ifdef HAVE_PTYS
383 #ifdef HAVE_PTY_H
384 #include <pty.h>
385 #endif
386 /* The file name of the pty opened by allocate_pty. */
387
388 static char pty_name[24];
389 #endif
390 \f
391 /* Compute the Lisp form of the process status, p->status, from
392 the numeric status that was returned by `wait'. */
393
394 static Lisp_Object status_convert (int);
395
396 static void
397 update_status (p)
398 struct Lisp_Process *p;
399 {
400 eassert (p->raw_status_new);
401 p->status = status_convert (p->raw_status);
402 p->raw_status_new = 0;
403 }
404
405 /* Convert a process status word in Unix format to
406 the list that we use internally. */
407
408 static Lisp_Object
409 status_convert (int w)
410 {
411 if (WIFSTOPPED (w))
412 return Fcons (Qstop, Fcons (make_number (WSTOPSIG (w)), Qnil));
413 else if (WIFEXITED (w))
414 return Fcons (Qexit, Fcons (make_number (WRETCODE (w)),
415 WCOREDUMP (w) ? Qt : Qnil));
416 else if (WIFSIGNALED (w))
417 return Fcons (Qsignal, Fcons (make_number (WTERMSIG (w)),
418 WCOREDUMP (w) ? Qt : Qnil));
419 else
420 return Qrun;
421 }
422
423 /* Given a status-list, extract the three pieces of information
424 and store them individually through the three pointers. */
425
426 static void
427 decode_status (l, symbol, code, coredump)
428 Lisp_Object l;
429 Lisp_Object *symbol;
430 int *code;
431 int *coredump;
432 {
433 Lisp_Object tem;
434
435 if (SYMBOLP (l))
436 {
437 *symbol = l;
438 *code = 0;
439 *coredump = 0;
440 }
441 else
442 {
443 *symbol = XCAR (l);
444 tem = XCDR (l);
445 *code = XFASTINT (XCAR (tem));
446 tem = XCDR (tem);
447 *coredump = !NILP (tem);
448 }
449 }
450
451 /* Return a string describing a process status list. */
452
453 static Lisp_Object
454 status_message (p)
455 struct Lisp_Process *p;
456 {
457 Lisp_Object status = p->status;
458 Lisp_Object symbol;
459 int code, coredump;
460 Lisp_Object string, string2;
461
462 decode_status (status, &symbol, &code, &coredump);
463
464 if (EQ (symbol, Qsignal) || EQ (symbol, Qstop))
465 {
466 char *signame;
467 synchronize_system_messages_locale ();
468 signame = strsignal (code);
469 if (signame == 0)
470 string = build_string ("unknown");
471 else
472 {
473 int c1, c2;
474
475 string = make_unibyte_string (signame, strlen (signame));
476 if (! NILP (Vlocale_coding_system))
477 string = (code_convert_string_norecord
478 (string, Vlocale_coding_system, 0));
479 c1 = STRING_CHAR ((char *) SDATA (string), 0);
480 c2 = DOWNCASE (c1);
481 if (c1 != c2)
482 Faset (string, make_number (0), make_number (c2));
483 }
484 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
485 return concat2 (string, string2);
486 }
487 else if (EQ (symbol, Qexit))
488 {
489 if (NETCONN1_P (p))
490 return build_string (code == 0 ? "deleted\n" : "connection broken by remote peer\n");
491 if (code == 0)
492 return build_string ("finished\n");
493 string = Fnumber_to_string (make_number (code));
494 string2 = build_string (coredump ? " (core dumped)\n" : "\n");
495 return concat3 (build_string ("exited abnormally with code "),
496 string, string2);
497 }
498 else if (EQ (symbol, Qfailed))
499 {
500 string = Fnumber_to_string (make_number (code));
501 string2 = build_string ("\n");
502 return concat3 (build_string ("failed with code "),
503 string, string2);
504 }
505 else
506 return Fcopy_sequence (Fsymbol_name (symbol));
507 }
508 \f
509 #ifdef HAVE_PTYS
510
511 /* Open an available pty, returning a file descriptor.
512 Return -1 on failure.
513 The file name of the terminal corresponding to the pty
514 is left in the variable pty_name. */
515
516 static int
517 allocate_pty ()
518 {
519 register int c, i;
520 int fd;
521
522 #ifdef PTY_ITERATION
523 PTY_ITERATION
524 #else
525 for (c = FIRST_PTY_LETTER; c <= 'z'; c++)
526 for (i = 0; i < 16; i++)
527 #endif
528 {
529 struct stat stb; /* Used in some PTY_OPEN. */
530 #ifdef PTY_NAME_SPRINTF
531 PTY_NAME_SPRINTF
532 #else
533 sprintf (pty_name, "/dev/pty%c%x", c, i);
534 #endif /* no PTY_NAME_SPRINTF */
535
536 #ifdef PTY_OPEN
537 PTY_OPEN;
538 #else /* no PTY_OPEN */
539 {
540 { /* Some systems name their pseudoterminals so that there are gaps in
541 the usual sequence - for example, on HP9000/S700 systems, there
542 are no pseudoterminals with names ending in 'f'. So we wait for
543 three failures in a row before deciding that we've reached the
544 end of the ptys. */
545 int failed_count = 0;
546
547 if (stat (pty_name, &stb) < 0)
548 {
549 failed_count++;
550 if (failed_count >= 3)
551 return -1;
552 }
553 else
554 failed_count = 0;
555 }
556 # ifdef O_NONBLOCK
557 fd = emacs_open (pty_name, O_RDWR | O_NONBLOCK, 0);
558 # else
559 fd = emacs_open (pty_name, O_RDWR | O_NDELAY, 0);
560 # endif
561 }
562 #endif /* no PTY_OPEN */
563
564 if (fd >= 0)
565 {
566 /* check to make certain that both sides are available
567 this avoids a nasty yet stupid bug in rlogins */
568 #ifdef PTY_TTY_NAME_SPRINTF
569 PTY_TTY_NAME_SPRINTF
570 #else
571 sprintf (pty_name, "/dev/tty%c%x", c, i);
572 #endif /* no PTY_TTY_NAME_SPRINTF */
573 if (access (pty_name, 6) != 0)
574 {
575 emacs_close (fd);
576 # ifndef __sgi
577 continue;
578 # else
579 return -1;
580 # endif /* __sgi */
581 }
582 setup_pty (fd);
583 return fd;
584 }
585 }
586 return -1;
587 }
588 #endif /* HAVE_PTYS */
589 \f
590 static Lisp_Object
591 make_process (name)
592 Lisp_Object name;
593 {
594 register Lisp_Object val, tem, name1;
595 register struct Lisp_Process *p;
596 char suffix[10];
597 register int i;
598
599 p = allocate_process ();
600
601 p->infd = -1;
602 p->outfd = -1;
603 p->tick = 0;
604 p->update_tick = 0;
605 p->pid = 0;
606 p->pty_flag = 0;
607 p->raw_status_new = 0;
608 p->status = Qrun;
609 p->mark = Fmake_marker ();
610 p->kill_without_query = 0;
611
612 #ifdef ADAPTIVE_READ_BUFFERING
613 p->adaptive_read_buffering = 0;
614 p->read_output_delay = 0;
615 p->read_output_skip = 0;
616 #endif
617
618 /* If name is already in use, modify it until it is unused. */
619
620 name1 = name;
621 for (i = 1; ; i++)
622 {
623 tem = Fget_process (name1);
624 if (NILP (tem)) break;
625 sprintf (suffix, "<%d>", i);
626 name1 = concat2 (name, build_string (suffix));
627 }
628 name = name1;
629 p->name = name;
630 XSETPROCESS (val, p);
631 Vprocess_alist = Fcons (Fcons (name, val), Vprocess_alist);
632 return val;
633 }
634
635 static void
636 remove_process (proc)
637 register Lisp_Object proc;
638 {
639 register Lisp_Object pair;
640
641 pair = Frassq (proc, Vprocess_alist);
642 Vprocess_alist = Fdelq (pair, Vprocess_alist);
643
644 deactivate_process (proc);
645 }
646
647 /* Setup coding systems of PROCESS. */
648
649 void
650 setup_process_coding_systems (process)
651 Lisp_Object process;
652 {
653 struct Lisp_Process *p = XPROCESS (process);
654 int inch = p->infd;
655 int outch = p->outfd;
656 Lisp_Object coding_system;
657
658 if (inch < 0 || outch < 0)
659 return;
660
661 if (!proc_decode_coding_system[inch])
662 proc_decode_coding_system[inch]
663 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
664 coding_system = p->decode_coding_system;
665 if (! NILP (p->filter))
666 ;
667 else if (BUFFERP (p->buffer))
668 {
669 if (NILP (XBUFFER (p->buffer)->enable_multibyte_characters))
670 coding_system = raw_text_coding_system (coding_system);
671 }
672 setup_coding_system (coding_system, proc_decode_coding_system[inch]);
673
674 if (!proc_encode_coding_system[outch])
675 proc_encode_coding_system[outch]
676 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
677 setup_coding_system (p->encode_coding_system,
678 proc_encode_coding_system[outch]);
679 }
680 \f
681 DEFUN ("processp", Fprocessp, Sprocessp, 1, 1, 0,
682 doc: /* Return t if OBJECT is a process. */)
683 (object)
684 Lisp_Object object;
685 {
686 return PROCESSP (object) ? Qt : Qnil;
687 }
688
689 DEFUN ("get-process", Fget_process, Sget_process, 1, 1, 0,
690 doc: /* Return the process named NAME, or nil if there is none. */)
691 (name)
692 register Lisp_Object name;
693 {
694 if (PROCESSP (name))
695 return name;
696 CHECK_STRING (name);
697 return Fcdr (Fassoc (name, Vprocess_alist));
698 }
699
700 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
701 doc: /* Return the (or a) process associated with BUFFER.
702 BUFFER may be a buffer or the name of one. */)
703 (buffer)
704 register Lisp_Object buffer;
705 {
706 register Lisp_Object buf, tail, proc;
707
708 if (NILP (buffer)) return Qnil;
709 buf = Fget_buffer (buffer);
710 if (NILP (buf)) return Qnil;
711
712 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
713 {
714 proc = Fcdr (XCAR (tail));
715 if (PROCESSP (proc) && EQ (XPROCESS (proc)->buffer, buf))
716 return proc;
717 }
718 return Qnil;
719 }
720
721 /* This is how commands for the user decode process arguments. It
722 accepts a process, a process name, a buffer, a buffer name, or nil.
723 Buffers denote the first process in the buffer, and nil denotes the
724 current buffer. */
725
726 static Lisp_Object
727 get_process (name)
728 register Lisp_Object name;
729 {
730 register Lisp_Object proc, obj;
731 if (STRINGP (name))
732 {
733 obj = Fget_process (name);
734 if (NILP (obj))
735 obj = Fget_buffer (name);
736 if (NILP (obj))
737 error ("Process %s does not exist", SDATA (name));
738 }
739 else if (NILP (name))
740 obj = Fcurrent_buffer ();
741 else
742 obj = name;
743
744 /* Now obj should be either a buffer object or a process object.
745 */
746 if (BUFFERP (obj))
747 {
748 proc = Fget_buffer_process (obj);
749 if (NILP (proc))
750 error ("Buffer %s has no process", SDATA (XBUFFER (obj)->name));
751 }
752 else
753 {
754 CHECK_PROCESS (obj);
755 proc = obj;
756 }
757 return proc;
758 }
759
760
761 #ifdef SIGCHLD
762 /* Fdelete_process promises to immediately forget about the process, but in
763 reality, Emacs needs to remember those processes until they have been
764 treated by sigchld_handler; otherwise this handler would consider the
765 process as being synchronous and say that the synchronous process is
766 dead. */
767 static Lisp_Object deleted_pid_list;
768 #endif
769
770 DEFUN ("delete-process", Fdelete_process, Sdelete_process, 1, 1, 0,
771 doc: /* Delete PROCESS: kill it and forget about it immediately.
772 PROCESS may be a process, a buffer, the name of a process or buffer, or
773 nil, indicating the current buffer's process. */)
774 (process)
775 register Lisp_Object process;
776 {
777 register struct Lisp_Process *p;
778
779 process = get_process (process);
780 p = XPROCESS (process);
781
782 p->raw_status_new = 0;
783 if (NETCONN1_P (p) || SERIALCONN1_P (p))
784 {
785 p->status = Fcons (Qexit, Fcons (make_number (0), Qnil));
786 p->tick = ++process_tick;
787 status_notify (p);
788 }
789 else if (p->infd >= 0)
790 {
791 #ifdef SIGCHLD
792 Lisp_Object symbol;
793 /* Assignment to EMACS_INT stops GCC whining about limited range
794 of data type. */
795 EMACS_INT pid = p->pid;
796
797 /* No problem storing the pid here, as it is still in Vprocess_alist. */
798 deleted_pid_list = Fcons (make_fixnum_or_float (pid),
799 /* GC treated elements set to nil. */
800 Fdelq (Qnil, deleted_pid_list));
801 /* If the process has already signaled, remove it from the list. */
802 if (p->raw_status_new)
803 update_status (p);
804 symbol = p->status;
805 if (CONSP (p->status))
806 symbol = XCAR (p->status);
807 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit))
808 deleted_pid_list
809 = Fdelete (make_fixnum_or_float (pid), deleted_pid_list);
810 else
811 #endif
812 {
813 Fkill_process (process, Qnil);
814 /* Do this now, since remove_process will make sigchld_handler do nothing. */
815 p->status
816 = Fcons (Qsignal, Fcons (make_number (SIGKILL), Qnil));
817 p->tick = ++process_tick;
818 status_notify (p);
819 }
820 }
821 remove_process (process);
822 return Qnil;
823 }
824 \f
825 DEFUN ("process-status", Fprocess_status, Sprocess_status, 1, 1, 0,
826 doc: /* Return the status of PROCESS.
827 The returned value is one of the following symbols:
828 run -- for a process that is running.
829 stop -- for a process stopped but continuable.
830 exit -- for a process that has exited.
831 signal -- for a process that has got a fatal signal.
832 open -- for a network stream connection that is open.
833 listen -- for a network stream server that is listening.
834 closed -- for a network stream connection that is closed.
835 connect -- when waiting for a non-blocking connection to complete.
836 failed -- when a non-blocking connection has failed.
837 nil -- if arg is a process name and no such process exists.
838 PROCESS may be a process, a buffer, the name of a process, or
839 nil, indicating the current buffer's process. */)
840 (process)
841 register Lisp_Object process;
842 {
843 register struct Lisp_Process *p;
844 register Lisp_Object status;
845
846 if (STRINGP (process))
847 process = Fget_process (process);
848 else
849 process = get_process (process);
850
851 if (NILP (process))
852 return process;
853
854 p = XPROCESS (process);
855 if (p->raw_status_new)
856 update_status (p);
857 status = p->status;
858 if (CONSP (status))
859 status = XCAR (status);
860 if (NETCONN1_P (p) || SERIALCONN1_P (p))
861 {
862 if (EQ (status, Qexit))
863 status = Qclosed;
864 else if (EQ (p->command, Qt))
865 status = Qstop;
866 else if (EQ (status, Qrun))
867 status = Qopen;
868 }
869 return status;
870 }
871
872 DEFUN ("process-exit-status", Fprocess_exit_status, Sprocess_exit_status,
873 1, 1, 0,
874 doc: /* Return the exit status of PROCESS or the signal number that killed it.
875 If PROCESS has not yet exited or died, return 0. */)
876 (process)
877 register Lisp_Object process;
878 {
879 CHECK_PROCESS (process);
880 if (XPROCESS (process)->raw_status_new)
881 update_status (XPROCESS (process));
882 if (CONSP (XPROCESS (process)->status))
883 return XCAR (XCDR (XPROCESS (process)->status));
884 return make_number (0);
885 }
886
887 DEFUN ("process-id", Fprocess_id, Sprocess_id, 1, 1, 0,
888 doc: /* Return the process id of PROCESS.
889 This is the pid of the external process which PROCESS uses or talks to.
890 For a network connection, this value is nil. */)
891 (process)
892 register Lisp_Object process;
893 {
894 /* Assignment to EMACS_INT stops GCC whining about limited range of
895 data type. */
896 EMACS_INT pid;
897
898 CHECK_PROCESS (process);
899 pid = XPROCESS (process)->pid;
900 return (pid ? make_fixnum_or_float (pid) : Qnil);
901 }
902
903 DEFUN ("process-name", Fprocess_name, Sprocess_name, 1, 1, 0,
904 doc: /* Return the name of PROCESS, as a string.
905 This is the name of the program invoked in PROCESS,
906 possibly modified to make it unique among process names. */)
907 (process)
908 register Lisp_Object process;
909 {
910 CHECK_PROCESS (process);
911 return XPROCESS (process)->name;
912 }
913
914 DEFUN ("process-command", Fprocess_command, Sprocess_command, 1, 1, 0,
915 doc: /* Return the command that was executed to start PROCESS.
916 This is a list of strings, the first string being the program executed
917 and the rest of the strings being the arguments given to it.
918 For a network or serial process, this is nil (process is running) or t
919 \(process is stopped). */)
920 (process)
921 register Lisp_Object process;
922 {
923 CHECK_PROCESS (process);
924 return XPROCESS (process)->command;
925 }
926
927 DEFUN ("process-tty-name", Fprocess_tty_name, Sprocess_tty_name, 1, 1, 0,
928 doc: /* Return the name of the terminal PROCESS uses, or nil if none.
929 This is the terminal that the process itself reads and writes on,
930 not the name of the pty that Emacs uses to talk with that terminal. */)
931 (process)
932 register Lisp_Object process;
933 {
934 CHECK_PROCESS (process);
935 return XPROCESS (process)->tty_name;
936 }
937
938 DEFUN ("set-process-buffer", Fset_process_buffer, Sset_process_buffer,
939 2, 2, 0,
940 doc: /* Set buffer associated with PROCESS to BUFFER (a buffer, or nil). */)
941 (process, buffer)
942 register Lisp_Object process, buffer;
943 {
944 struct Lisp_Process *p;
945
946 CHECK_PROCESS (process);
947 if (!NILP (buffer))
948 CHECK_BUFFER (buffer);
949 p = XPROCESS (process);
950 p->buffer = buffer;
951 if (NETCONN1_P (p) || SERIALCONN1_P (p))
952 p->childp = Fplist_put (p->childp, QCbuffer, buffer);
953 setup_process_coding_systems (process);
954 return buffer;
955 }
956
957 DEFUN ("process-buffer", Fprocess_buffer, Sprocess_buffer,
958 1, 1, 0,
959 doc: /* Return the buffer PROCESS is associated with.
960 Output from PROCESS is inserted in this buffer unless PROCESS has a filter. */)
961 (process)
962 register Lisp_Object process;
963 {
964 CHECK_PROCESS (process);
965 return XPROCESS (process)->buffer;
966 }
967
968 DEFUN ("process-mark", Fprocess_mark, Sprocess_mark,
969 1, 1, 0,
970 doc: /* Return the marker for the end of the last output from PROCESS. */)
971 (process)
972 register Lisp_Object process;
973 {
974 CHECK_PROCESS (process);
975 return XPROCESS (process)->mark;
976 }
977
978 DEFUN ("set-process-filter", Fset_process_filter, Sset_process_filter,
979 2, 2, 0,
980 doc: /* Give PROCESS the filter function FILTER; nil means no filter.
981 A value of t means stop accepting output from the process.
982
983 When a process has a filter, its buffer is not used for output.
984 Instead, each time it does output, the entire string of output is
985 passed to the filter.
986
987 The filter gets two arguments: the process and the string of output.
988 The string argument is normally a multibyte string, except:
989 - if the process' input coding system is no-conversion or raw-text,
990 it is a unibyte string (the non-converted input), or else
991 - if `default-enable-multibyte-characters' is nil, it is a unibyte
992 string (the result of converting the decoded input multibyte
993 string to unibyte with `string-make-unibyte'). */)
994 (process, filter)
995 register Lisp_Object process, filter;
996 {
997 struct Lisp_Process *p;
998
999 CHECK_PROCESS (process);
1000 p = XPROCESS (process);
1001
1002 /* Don't signal an error if the process' input file descriptor
1003 is closed. This could make debugging Lisp more difficult,
1004 for example when doing something like
1005
1006 (setq process (start-process ...))
1007 (debug)
1008 (set-process-filter process ...) */
1009
1010 if (p->infd >= 0)
1011 {
1012 if (EQ (filter, Qt) && !EQ (p->status, Qlisten))
1013 {
1014 FD_CLR (p->infd, &input_wait_mask);
1015 FD_CLR (p->infd, &non_keyboard_wait_mask);
1016 }
1017 else if (EQ (p->filter, Qt)
1018 /* Network or serial process not stopped: */
1019 && !EQ (p->command, Qt))
1020 {
1021 FD_SET (p->infd, &input_wait_mask);
1022 FD_SET (p->infd, &non_keyboard_wait_mask);
1023 }
1024 }
1025
1026 p->filter = filter;
1027 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1028 p->childp = Fplist_put (p->childp, QCfilter, filter);
1029 setup_process_coding_systems (process);
1030 return filter;
1031 }
1032
1033 DEFUN ("process-filter", Fprocess_filter, Sprocess_filter,
1034 1, 1, 0,
1035 doc: /* Returns the filter function of PROCESS; nil if none.
1036 See `set-process-filter' for more info on filter functions. */)
1037 (process)
1038 register Lisp_Object process;
1039 {
1040 CHECK_PROCESS (process);
1041 return XPROCESS (process)->filter;
1042 }
1043
1044 DEFUN ("set-process-sentinel", Fset_process_sentinel, Sset_process_sentinel,
1045 2, 2, 0,
1046 doc: /* Give PROCESS the sentinel SENTINEL; nil for none.
1047 The sentinel is called as a function when the process changes state.
1048 It gets two arguments: the process, and a string describing the change. */)
1049 (process, sentinel)
1050 register Lisp_Object process, sentinel;
1051 {
1052 struct Lisp_Process *p;
1053
1054 CHECK_PROCESS (process);
1055 p = XPROCESS (process);
1056
1057 p->sentinel = sentinel;
1058 if (NETCONN1_P (p) || SERIALCONN1_P (p))
1059 p->childp = Fplist_put (p->childp, QCsentinel, sentinel);
1060 return sentinel;
1061 }
1062
1063 DEFUN ("process-sentinel", Fprocess_sentinel, Sprocess_sentinel,
1064 1, 1, 0,
1065 doc: /* Return the sentinel of PROCESS; nil if none.
1066 See `set-process-sentinel' for more info on sentinels. */)
1067 (process)
1068 register Lisp_Object process;
1069 {
1070 CHECK_PROCESS (process);
1071 return XPROCESS (process)->sentinel;
1072 }
1073
1074 DEFUN ("set-process-window-size", Fset_process_window_size,
1075 Sset_process_window_size, 3, 3, 0,
1076 doc: /* Tell PROCESS that it has logical window size HEIGHT and WIDTH. */)
1077 (process, height, width)
1078 register Lisp_Object process, height, width;
1079 {
1080 CHECK_PROCESS (process);
1081 CHECK_NATNUM (height);
1082 CHECK_NATNUM (width);
1083
1084 if (XPROCESS (process)->infd < 0
1085 || set_window_size (XPROCESS (process)->infd,
1086 XINT (height), XINT (width)) <= 0)
1087 return Qnil;
1088 else
1089 return Qt;
1090 }
1091
1092 DEFUN ("set-process-inherit-coding-system-flag",
1093 Fset_process_inherit_coding_system_flag,
1094 Sset_process_inherit_coding_system_flag, 2, 2, 0,
1095 doc: /* Determine whether buffer of PROCESS will inherit coding-system.
1096 If the second argument FLAG is non-nil, then the variable
1097 `buffer-file-coding-system' of the buffer associated with PROCESS
1098 will be bound to the value of the coding system used to decode
1099 the process output.
1100
1101 This is useful when the coding system specified for the process buffer
1102 leaves either the character code conversion or the end-of-line conversion
1103 unspecified, or if the coding system used to decode the process output
1104 is more appropriate for saving the process buffer.
1105
1106 Binding the variable `inherit-process-coding-system' to non-nil before
1107 starting the process is an alternative way of setting the inherit flag
1108 for the process which will run. */)
1109 (process, flag)
1110 register Lisp_Object process, flag;
1111 {
1112 CHECK_PROCESS (process);
1113 XPROCESS (process)->inherit_coding_system_flag = !NILP (flag);
1114 return flag;
1115 }
1116
1117 DEFUN ("process-inherit-coding-system-flag",
1118 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
1119 1, 1, 0,
1120 doc: /* Return the value of inherit-coding-system flag for PROCESS.
1121 If this flag is t, `buffer-file-coding-system' of the buffer
1122 associated with PROCESS will inherit the coding system used to decode
1123 the process output. */)
1124 (process)
1125 register Lisp_Object process;
1126 {
1127 CHECK_PROCESS (process);
1128 return XPROCESS (process)->inherit_coding_system_flag ? Qt : Qnil;
1129 }
1130
1131 DEFUN ("set-process-query-on-exit-flag",
1132 Fset_process_query_on_exit_flag, Sset_process_query_on_exit_flag,
1133 2, 2, 0,
1134 doc: /* Specify if query is needed for PROCESS when Emacs is exited.
1135 If the second argument FLAG is non-nil, Emacs will query the user before
1136 exiting if PROCESS is running. */)
1137 (process, flag)
1138 register Lisp_Object process, flag;
1139 {
1140 CHECK_PROCESS (process);
1141 XPROCESS (process)->kill_without_query = NILP (flag);
1142 return flag;
1143 }
1144
1145 DEFUN ("process-query-on-exit-flag",
1146 Fprocess_query_on_exit_flag, Sprocess_query_on_exit_flag,
1147 1, 1, 0,
1148 doc: /* Return the current value of query-on-exit flag for PROCESS. */)
1149 (process)
1150 register Lisp_Object process;
1151 {
1152 CHECK_PROCESS (process);
1153 return (XPROCESS (process)->kill_without_query ? Qnil : Qt);
1154 }
1155
1156 #ifdef DATAGRAM_SOCKETS
1157 Lisp_Object Fprocess_datagram_address ();
1158 #endif
1159
1160 DEFUN ("process-contact", Fprocess_contact, Sprocess_contact,
1161 1, 2, 0,
1162 doc: /* Return the contact info of PROCESS; t for a real child.
1163 For a network or serial connection, the value depends on the optional
1164 KEY arg. If KEY is nil, value is a cons cell of the form (HOST
1165 SERVICE) for a network connection or (PORT SPEED) for a serial
1166 connection. If KEY is t, the complete contact information for the
1167 connection is returned, else the specific value for the keyword KEY is
1168 returned. See `make-network-process' or `make-serial-process' for a
1169 list of keywords. */)
1170 (process, key)
1171 register Lisp_Object process, key;
1172 {
1173 Lisp_Object contact;
1174
1175 CHECK_PROCESS (process);
1176 contact = XPROCESS (process)->childp;
1177
1178 #ifdef DATAGRAM_SOCKETS
1179 if (DATAGRAM_CONN_P (process)
1180 && (EQ (key, Qt) || EQ (key, QCremote)))
1181 contact = Fplist_put (contact, QCremote,
1182 Fprocess_datagram_address (process));
1183 #endif
1184
1185 if ((!NETCONN_P (process) && !SERIALCONN_P (process)) || EQ (key, Qt))
1186 return contact;
1187 if (NILP (key) && NETCONN_P (process))
1188 return Fcons (Fplist_get (contact, QChost),
1189 Fcons (Fplist_get (contact, QCservice), Qnil));
1190 if (NILP (key) && SERIALCONN_P (process))
1191 return Fcons (Fplist_get (contact, QCport),
1192 Fcons (Fplist_get (contact, QCspeed), Qnil));
1193 return Fplist_get (contact, key);
1194 }
1195
1196 DEFUN ("process-plist", Fprocess_plist, Sprocess_plist,
1197 1, 1, 0,
1198 doc: /* Return the plist of PROCESS. */)
1199 (process)
1200 register Lisp_Object process;
1201 {
1202 CHECK_PROCESS (process);
1203 return XPROCESS (process)->plist;
1204 }
1205
1206 DEFUN ("set-process-plist", Fset_process_plist, Sset_process_plist,
1207 2, 2, 0,
1208 doc: /* Replace the plist of PROCESS with PLIST. Returns PLIST. */)
1209 (process, plist)
1210 register Lisp_Object process, plist;
1211 {
1212 CHECK_PROCESS (process);
1213 CHECK_LIST (plist);
1214
1215 XPROCESS (process)->plist = plist;
1216 return plist;
1217 }
1218
1219 #if 0 /* Turned off because we don't currently record this info
1220 in the process. Perhaps add it. */
1221 DEFUN ("process-connection", Fprocess_connection, Sprocess_connection, 1, 1, 0,
1222 doc: /* Return the connection type of PROCESS.
1223 The value is nil for a pipe, t or `pty' for a pty, or `stream' for
1224 a socket connection. */)
1225 (process)
1226 Lisp_Object process;
1227 {
1228 return XPROCESS (process)->type;
1229 }
1230 #endif
1231
1232 DEFUN ("process-type", Fprocess_type, Sprocess_type, 1, 1, 0,
1233 doc: /* Return the connection type of PROCESS.
1234 The value is either the symbol `real', `network', or `serial'.
1235 PROCESS may be a process, a buffer, the name of a process or buffer, or
1236 nil, indicating the current buffer's process. */)
1237 (process)
1238 Lisp_Object process;
1239 {
1240 Lisp_Object proc;
1241 proc = get_process (process);
1242 return XPROCESS (proc)->type;
1243 }
1244
1245 #ifdef HAVE_SOCKETS
1246 DEFUN ("format-network-address", Fformat_network_address, Sformat_network_address,
1247 1, 2, 0,
1248 doc: /* Convert network ADDRESS from internal format to a string.
1249 A 4 or 5 element vector represents an IPv4 address (with port number).
1250 An 8 or 9 element vector represents an IPv6 address (with port number).
1251 If optional second argument OMIT-PORT is non-nil, don't include a port
1252 number in the string, even when present in ADDRESS.
1253 Returns nil if format of ADDRESS is invalid. */)
1254 (address, omit_port)
1255 Lisp_Object address, omit_port;
1256 {
1257 if (NILP (address))
1258 return Qnil;
1259
1260 if (STRINGP (address)) /* AF_LOCAL */
1261 return address;
1262
1263 if (VECTORP (address)) /* AF_INET or AF_INET6 */
1264 {
1265 register struct Lisp_Vector *p = XVECTOR (address);
1266 Lisp_Object args[10];
1267 int nargs, i;
1268
1269 if (p->size == 4 || (p->size == 5 && !NILP (omit_port)))
1270 {
1271 args[0] = build_string ("%d.%d.%d.%d");
1272 nargs = 4;
1273 }
1274 else if (p->size == 5)
1275 {
1276 args[0] = build_string ("%d.%d.%d.%d:%d");
1277 nargs = 5;
1278 }
1279 else if (p->size == 8 || (p->size == 9 && !NILP (omit_port)))
1280 {
1281 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
1282 nargs = 8;
1283 }
1284 else if (p->size == 9)
1285 {
1286 args[0] = build_string ("[%x:%x:%x:%x:%x:%x:%x:%x]:%d");
1287 nargs = 9;
1288 }
1289 else
1290 return Qnil;
1291
1292 for (i = 0; i < nargs; i++)
1293 {
1294 EMACS_INT element = XINT (p->contents[i]);
1295
1296 if (element < 0 || element > 65535)
1297 return Qnil;
1298
1299 if (nargs <= 5 /* IPv4 */
1300 && i < 4 /* host, not port */
1301 && element > 255)
1302 return Qnil;
1303
1304 args[i+1] = p->contents[i];
1305 }
1306
1307 return Fformat (nargs+1, args);
1308 }
1309
1310 if (CONSP (address))
1311 {
1312 Lisp_Object args[2];
1313 args[0] = build_string ("<Family %d>");
1314 args[1] = Fcar (address);
1315 return Fformat (2, args);
1316 }
1317
1318 return Qnil;
1319 }
1320 #endif
1321 \f
1322 static Lisp_Object
1323 list_processes_1 (query_only)
1324 Lisp_Object query_only;
1325 {
1326 register Lisp_Object tail, tem;
1327 Lisp_Object proc, minspace, tem1;
1328 register struct Lisp_Process *p;
1329 char tembuf[300];
1330 int w_proc, w_buffer, w_tty;
1331 int exited = 0;
1332 Lisp_Object i_status, i_buffer, i_tty, i_command;
1333
1334 w_proc = 4; /* Proc */
1335 w_buffer = 6; /* Buffer */
1336 w_tty = 0; /* Omit if no ttys */
1337
1338 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1339 {
1340 int i;
1341
1342 proc = Fcdr (XCAR (tail));
1343 p = XPROCESS (proc);
1344 if (NILP (p->type))
1345 continue;
1346 if (!NILP (query_only) && p->kill_without_query)
1347 continue;
1348 if (STRINGP (p->name)
1349 && ( i = SCHARS (p->name), (i > w_proc)))
1350 w_proc = i;
1351 if (!NILP (p->buffer))
1352 {
1353 if (NILP (XBUFFER (p->buffer)->name))
1354 {
1355 if (w_buffer < 8)
1356 w_buffer = 8; /* (Killed) */
1357 }
1358 else if ((i = SCHARS (XBUFFER (p->buffer)->name), (i > w_buffer)))
1359 w_buffer = i;
1360 }
1361 if (STRINGP (p->tty_name)
1362 && (i = SCHARS (p->tty_name), (i > w_tty)))
1363 w_tty = i;
1364 }
1365
1366 XSETFASTINT (i_status, w_proc + 1);
1367 XSETFASTINT (i_buffer, XFASTINT (i_status) + 9);
1368 if (w_tty)
1369 {
1370 XSETFASTINT (i_tty, XFASTINT (i_buffer) + w_buffer + 1);
1371 XSETFASTINT (i_command, XFASTINT (i_tty) + w_tty + 1);
1372 }
1373 else
1374 {
1375 i_tty = Qnil;
1376 XSETFASTINT (i_command, XFASTINT (i_buffer) + w_buffer + 1);
1377 }
1378
1379 XSETFASTINT (minspace, 1);
1380
1381 set_buffer_internal (XBUFFER (Vstandard_output));
1382 current_buffer->undo_list = Qt;
1383
1384 current_buffer->truncate_lines = Qt;
1385
1386 write_string ("Proc", -1);
1387 Findent_to (i_status, minspace); write_string ("Status", -1);
1388 Findent_to (i_buffer, minspace); write_string ("Buffer", -1);
1389 if (!NILP (i_tty))
1390 {
1391 Findent_to (i_tty, minspace); write_string ("Tty", -1);
1392 }
1393 Findent_to (i_command, minspace); write_string ("Command", -1);
1394 write_string ("\n", -1);
1395
1396 write_string ("----", -1);
1397 Findent_to (i_status, minspace); write_string ("------", -1);
1398 Findent_to (i_buffer, minspace); write_string ("------", -1);
1399 if (!NILP (i_tty))
1400 {
1401 Findent_to (i_tty, minspace); write_string ("---", -1);
1402 }
1403 Findent_to (i_command, minspace); write_string ("-------", -1);
1404 write_string ("\n", -1);
1405
1406 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
1407 {
1408 Lisp_Object symbol;
1409
1410 proc = Fcdr (XCAR (tail));
1411 p = XPROCESS (proc);
1412 if (NILP (p->type))
1413 continue;
1414 if (!NILP (query_only) && p->kill_without_query)
1415 continue;
1416
1417 Finsert (1, &p->name);
1418 Findent_to (i_status, minspace);
1419
1420 if (p->raw_status_new)
1421 update_status (p);
1422 symbol = p->status;
1423 if (CONSP (p->status))
1424 symbol = XCAR (p->status);
1425
1426 if (EQ (symbol, Qsignal))
1427 {
1428 Lisp_Object tem;
1429 tem = Fcar (Fcdr (p->status));
1430 Fprinc (symbol, Qnil);
1431 }
1432 else if (NETCONN1_P (p) || SERIALCONN1_P (p))
1433 {
1434 if (EQ (symbol, Qexit))
1435 write_string ("closed", -1);
1436 else if (EQ (p->command, Qt))
1437 write_string ("stopped", -1);
1438 else if (EQ (symbol, Qrun))
1439 write_string ("open", -1);
1440 else
1441 Fprinc (symbol, Qnil);
1442 }
1443 else if (SERIALCONN1_P (p))
1444 {
1445 write_string ("running", -1);
1446 }
1447 else
1448 Fprinc (symbol, Qnil);
1449
1450 if (EQ (symbol, Qexit))
1451 {
1452 Lisp_Object tem;
1453 tem = Fcar (Fcdr (p->status));
1454 if (XFASTINT (tem))
1455 {
1456 sprintf (tembuf, " %d", (int) XFASTINT (tem));
1457 write_string (tembuf, -1);
1458 }
1459 }
1460
1461 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit) || EQ (symbol, Qclosed))
1462 exited++;
1463
1464 Findent_to (i_buffer, minspace);
1465 if (NILP (p->buffer))
1466 insert_string ("(none)");
1467 else if (NILP (XBUFFER (p->buffer)->name))
1468 insert_string ("(Killed)");
1469 else
1470 Finsert (1, &XBUFFER (p->buffer)->name);
1471
1472 if (!NILP (i_tty))
1473 {
1474 Findent_to (i_tty, minspace);
1475 if (STRINGP (p->tty_name))
1476 Finsert (1, &p->tty_name);
1477 }
1478
1479 Findent_to (i_command, minspace);
1480
1481 if (EQ (p->status, Qlisten))
1482 {
1483 Lisp_Object port = Fplist_get (p->childp, QCservice);
1484 if (INTEGERP (port))
1485 port = Fnumber_to_string (port);
1486 if (NILP (port))
1487 port = Fformat_network_address (Fplist_get (p->childp, QClocal), Qnil);
1488 sprintf (tembuf, "(network %s server on %s)\n",
1489 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1490 (STRINGP (port) ? (char *)SDATA (port) : "?"));
1491 insert_string (tembuf);
1492 }
1493 else if (NETCONN1_P (p))
1494 {
1495 /* For a local socket, there is no host name,
1496 so display service instead. */
1497 Lisp_Object host = Fplist_get (p->childp, QChost);
1498 if (!STRINGP (host))
1499 {
1500 host = Fplist_get (p->childp, QCservice);
1501 if (INTEGERP (host))
1502 host = Fnumber_to_string (host);
1503 }
1504 if (NILP (host))
1505 host = Fformat_network_address (Fplist_get (p->childp, QCremote), Qnil);
1506 sprintf (tembuf, "(network %s connection to %s)\n",
1507 (DATAGRAM_CHAN_P (p->infd) ? "datagram" : "stream"),
1508 (STRINGP (host) ? (char *)SDATA (host) : "?"));
1509 insert_string (tembuf);
1510 }
1511 else if (SERIALCONN1_P (p))
1512 {
1513 Lisp_Object port = Fplist_get (p->childp, QCport);
1514 Lisp_Object speed = Fplist_get (p->childp, QCspeed);
1515 insert_string ("(serial port ");
1516 if (STRINGP (port))
1517 insert_string (SDATA (port));
1518 else
1519 insert_string ("?");
1520 if (INTEGERP (speed))
1521 {
1522 sprintf (tembuf, " at %d b/s", XINT (speed));
1523 insert_string (tembuf);
1524 }
1525 insert_string (")\n");
1526 }
1527 else
1528 {
1529 tem = p->command;
1530 while (1)
1531 {
1532 tem1 = Fcar (tem);
1533 Finsert (1, &tem1);
1534 tem = Fcdr (tem);
1535 if (NILP (tem))
1536 break;
1537 insert_string (" ");
1538 }
1539 insert_string ("\n");
1540 }
1541 }
1542 if (exited)
1543 status_notify (NULL);
1544 return Qnil;
1545 }
1546
1547 DEFUN ("list-processes", Flist_processes, Slist_processes, 0, 1, "P",
1548 doc: /* Display a list of all processes.
1549 If optional argument QUERY-ONLY is non-nil, only processes with
1550 the query-on-exit flag set will be listed.
1551 Any process listed as exited or signaled is actually eliminated
1552 after the listing is made. */)
1553 (query_only)
1554 Lisp_Object query_only;
1555 {
1556 internal_with_output_to_temp_buffer ("*Process List*",
1557 list_processes_1, query_only);
1558 return Qnil;
1559 }
1560
1561 DEFUN ("process-list", Fprocess_list, Sprocess_list, 0, 0, 0,
1562 doc: /* Return a list of all processes. */)
1563 ()
1564 {
1565 return Fmapcar (Qcdr, Vprocess_alist);
1566 }
1567 \f
1568 /* Starting asynchronous inferior processes. */
1569
1570 static Lisp_Object start_process_unwind ();
1571
1572 DEFUN ("start-process", Fstart_process, Sstart_process, 3, MANY, 0,
1573 doc: /* Start a program in a subprocess. Return the process object for it.
1574 NAME is name for process. It is modified if necessary to make it unique.
1575 BUFFER is the buffer (or buffer name) to associate with the process.
1576
1577 Process output (both standard output and standard error streams) goes
1578 at end of BUFFER, unless you specify an output stream or filter
1579 function to handle the output. BUFFER may also be nil, meaning that
1580 this process is not associated with any buffer.
1581
1582 PROGRAM is the program file name. It is searched for in PATH.
1583 Remaining arguments are strings to give program as arguments.
1584
1585 If you want to separate standard output from standard error, invoke
1586 the command through a shell and redirect one of them using the shell
1587 syntax.
1588
1589 usage: (start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS) */)
1590 (nargs, args)
1591 int nargs;
1592 register Lisp_Object *args;
1593 {
1594 Lisp_Object buffer, name, program, proc, current_dir, tem;
1595 register unsigned char **new_argv;
1596 register int i;
1597 int count = SPECPDL_INDEX ();
1598
1599 buffer = args[1];
1600 if (!NILP (buffer))
1601 buffer = Fget_buffer_create (buffer);
1602
1603 /* Make sure that the child will be able to chdir to the current
1604 buffer's current directory, or its unhandled equivalent. We
1605 can't just have the child check for an error when it does the
1606 chdir, since it's in a vfork.
1607
1608 We have to GCPRO around this because Fexpand_file_name and
1609 Funhandled_file_name_directory might call a file name handling
1610 function. The argument list is protected by the caller, so all
1611 we really have to worry about is buffer. */
1612 {
1613 struct gcpro gcpro1, gcpro2;
1614
1615 current_dir = current_buffer->directory;
1616
1617 GCPRO2 (buffer, current_dir);
1618
1619 current_dir = Funhandled_file_name_directory (current_dir);
1620 if (NILP (current_dir))
1621 /* If the file name handler says that current_dir is unreachable, use
1622 a sensible default. */
1623 current_dir = build_string ("~/");
1624 current_dir = expand_and_dir_to_file (current_dir, Qnil);
1625 if (NILP (Ffile_accessible_directory_p (current_dir)))
1626 report_file_error ("Setting current directory",
1627 Fcons (current_buffer->directory, Qnil));
1628
1629 UNGCPRO;
1630 }
1631
1632 name = args[0];
1633 CHECK_STRING (name);
1634
1635 program = args[2];
1636
1637 CHECK_STRING (program);
1638
1639 proc = make_process (name);
1640 /* If an error occurs and we can't start the process, we want to
1641 remove it from the process list. This means that each error
1642 check in create_process doesn't need to call remove_process
1643 itself; it's all taken care of here. */
1644 record_unwind_protect (start_process_unwind, proc);
1645
1646 XPROCESS (proc)->childp = Qt;
1647 XPROCESS (proc)->plist = Qnil;
1648 XPROCESS (proc)->type = Qreal;
1649 XPROCESS (proc)->buffer = buffer;
1650 XPROCESS (proc)->sentinel = Qnil;
1651 XPROCESS (proc)->filter = Qnil;
1652 XPROCESS (proc)->command = Flist (nargs - 2, args + 2);
1653
1654 #ifdef ADAPTIVE_READ_BUFFERING
1655 XPROCESS (proc)->adaptive_read_buffering
1656 = (NILP (Vprocess_adaptive_read_buffering) ? 0
1657 : EQ (Vprocess_adaptive_read_buffering, Qt) ? 1 : 2);
1658 #endif
1659
1660 /* Make the process marker point into the process buffer (if any). */
1661 if (BUFFERP (buffer))
1662 set_marker_both (XPROCESS (proc)->mark, buffer,
1663 BUF_ZV (XBUFFER (buffer)),
1664 BUF_ZV_BYTE (XBUFFER (buffer)));
1665
1666 {
1667 /* Decide coding systems for communicating with the process. Here
1668 we don't setup the structure coding_system nor pay attention to
1669 unibyte mode. They are done in create_process. */
1670
1671 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
1672 Lisp_Object coding_systems = Qt;
1673 Lisp_Object val, *args2;
1674 struct gcpro gcpro1, gcpro2;
1675
1676 val = Vcoding_system_for_read;
1677 if (NILP (val))
1678 {
1679 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof *args2);
1680 args2[0] = Qstart_process;
1681 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1682 GCPRO2 (proc, current_dir);
1683 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1684 UNGCPRO;
1685 if (CONSP (coding_systems))
1686 val = XCAR (coding_systems);
1687 else if (CONSP (Vdefault_process_coding_system))
1688 val = XCAR (Vdefault_process_coding_system);
1689 }
1690 XPROCESS (proc)->decode_coding_system = val;
1691
1692 val = Vcoding_system_for_write;
1693 if (NILP (val))
1694 {
1695 if (EQ (coding_systems, Qt))
1696 {
1697 args2 = (Lisp_Object *) alloca ((nargs + 1) * sizeof args2);
1698 args2[0] = Qstart_process;
1699 for (i = 0; i < nargs; i++) args2[i + 1] = args[i];
1700 GCPRO2 (proc, current_dir);
1701 coding_systems = Ffind_operation_coding_system (nargs + 1, args2);
1702 UNGCPRO;
1703 }
1704 if (CONSP (coding_systems))
1705 val = XCDR (coding_systems);
1706 else if (CONSP (Vdefault_process_coding_system))
1707 val = XCDR (Vdefault_process_coding_system);
1708 }
1709 XPROCESS (proc)->encode_coding_system = val;
1710 }
1711
1712 /* If program file name is not absolute, search our path for it.
1713 Put the name we will really use in TEM. */
1714 if (!IS_DIRECTORY_SEP (SREF (program, 0))
1715 && !(SCHARS (program) > 1
1716 && IS_DEVICE_SEP (SREF (program, 1))))
1717 {
1718 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
1719
1720 tem = Qnil;
1721 GCPRO4 (name, program, buffer, current_dir);
1722 openp (Vexec_path, program, Vexec_suffixes, &tem, make_number (X_OK));
1723 UNGCPRO;
1724 if (NILP (tem))
1725 report_file_error ("Searching for program", Fcons (program, Qnil));
1726 tem = Fexpand_file_name (tem, Qnil);
1727 }
1728 else
1729 {
1730 if (!NILP (Ffile_directory_p (program)))
1731 error ("Specified program for new process is a directory");
1732 tem = program;
1733 }
1734
1735 /* If program file name starts with /: for quoting a magic name,
1736 discard that. */
1737 if (SBYTES (tem) > 2 && SREF (tem, 0) == '/'
1738 && SREF (tem, 1) == ':')
1739 tem = Fsubstring (tem, make_number (2), Qnil);
1740
1741 {
1742 struct gcpro gcpro1;
1743 GCPRO1 (tem);
1744
1745 /* Encode the file name and put it in NEW_ARGV.
1746 That's where the child will use it to execute the program. */
1747 tem = Fcons (ENCODE_FILE (tem), Qnil);
1748
1749 /* Here we encode arguments by the coding system used for sending
1750 data to the process. We don't support using different coding
1751 systems for encoding arguments and for encoding data sent to the
1752 process. */
1753
1754 for (i = 3; i < nargs; i++)
1755 {
1756 tem = Fcons (args[i], tem);
1757 CHECK_STRING (XCAR (tem));
1758 if (STRING_MULTIBYTE (XCAR (tem)))
1759 XSETCAR (tem,
1760 code_convert_string_norecord
1761 (XCAR (tem), XPROCESS (proc)->encode_coding_system, 1));
1762 }
1763
1764 UNGCPRO;
1765 }
1766
1767 /* Now that everything is encoded we can collect the strings into
1768 NEW_ARGV. */
1769 new_argv = (unsigned char **) alloca ((nargs - 1) * sizeof (char *));
1770 new_argv[nargs - 2] = 0;
1771
1772 for (i = nargs - 3; i >= 0; i--)
1773 {
1774 new_argv[i] = SDATA (XCAR (tem));
1775 tem = XCDR (tem);
1776 }
1777
1778 XPROCESS (proc)->decoding_buf = make_uninit_string (0);
1779 XPROCESS (proc)->decoding_carryover = 0;
1780 XPROCESS (proc)->encoding_buf = make_uninit_string (0);
1781
1782 XPROCESS (proc)->inherit_coding_system_flag
1783 = !(NILP (buffer) || !inherit_process_coding_system);
1784
1785 create_process (proc, (char **) new_argv, current_dir);
1786
1787 return unbind_to (count, proc);
1788 }
1789
1790 /* This function is the unwind_protect form for Fstart_process. If
1791 PROC doesn't have its pid set, then we know someone has signaled
1792 an error and the process wasn't started successfully, so we should
1793 remove it from the process list. */
1794 static Lisp_Object
1795 start_process_unwind (proc)
1796 Lisp_Object proc;
1797 {
1798 if (!PROCESSP (proc))
1799 abort ();
1800
1801 /* Was PROC started successfully? */
1802 if (XPROCESS (proc)->pid <= 0)
1803 remove_process (proc);
1804
1805 return Qnil;
1806 }
1807
1808 static void
1809 create_process_1 (timer)
1810 struct atimer *timer;
1811 {
1812 /* Nothing to do. */
1813 }
1814
1815
1816 #if 0 /* This doesn't work; see the note before sigchld_handler. */
1817 #ifdef USG
1818 #ifdef SIGCHLD
1819 /* Mimic blocking of signals on system V, which doesn't really have it. */
1820
1821 /* Nonzero means we got a SIGCHLD when it was supposed to be blocked. */
1822 int sigchld_deferred;
1823
1824 SIGTYPE
1825 create_process_sigchld ()
1826 {
1827 signal (SIGCHLD, create_process_sigchld);
1828
1829 sigchld_deferred = 1;
1830 }
1831 #endif
1832 #endif
1833 #endif
1834
1835 void
1836 create_process (process, new_argv, current_dir)
1837 Lisp_Object process;
1838 char **new_argv;
1839 Lisp_Object current_dir;
1840 {
1841 int inchannel, outchannel;
1842 pid_t pid;
1843 int sv[2];
1844 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1845 int wait_child_setup[2];
1846 #endif
1847 #ifdef POSIX_SIGNALS
1848 sigset_t procmask;
1849 sigset_t blocked;
1850 struct sigaction sigint_action;
1851 struct sigaction sigquit_action;
1852 #ifdef AIX
1853 struct sigaction sighup_action;
1854 #endif
1855 #else /* !POSIX_SIGNALS */
1856 #if 0
1857 #ifdef SIGCHLD
1858 SIGTYPE (*sigchld)();
1859 #endif
1860 #endif /* 0 */
1861 #endif /* !POSIX_SIGNALS */
1862 /* Use volatile to protect variables from being clobbered by longjmp. */
1863 volatile int forkin, forkout;
1864 volatile int pty_flag = 0;
1865 #ifndef USE_CRT_DLL
1866 extern char **environ;
1867 #endif
1868
1869 inchannel = outchannel = -1;
1870
1871 #ifdef HAVE_PTYS
1872 if (!NILP (Vprocess_connection_type))
1873 outchannel = inchannel = allocate_pty ();
1874
1875 if (inchannel >= 0)
1876 {
1877 #if ! defined (USG) || defined (USG_SUBTTY_WORKS)
1878 /* On most USG systems it does not work to open the pty's tty here,
1879 then close it and reopen it in the child. */
1880 #ifdef O_NOCTTY
1881 /* Don't let this terminal become our controlling terminal
1882 (in case we don't have one). */
1883 forkout = forkin = emacs_open (pty_name, O_RDWR | O_NOCTTY, 0);
1884 #else
1885 forkout = forkin = emacs_open (pty_name, O_RDWR, 0);
1886 #endif
1887 if (forkin < 0)
1888 report_file_error ("Opening pty", Qnil);
1889 #else
1890 forkin = forkout = -1;
1891 #endif /* not USG, or USG_SUBTTY_WORKS */
1892 pty_flag = 1;
1893 }
1894 else
1895 #endif /* HAVE_PTYS */
1896 {
1897 int tem;
1898 tem = pipe (sv);
1899 if (tem < 0)
1900 report_file_error ("Creating pipe", Qnil);
1901 inchannel = sv[0];
1902 forkout = sv[1];
1903 tem = pipe (sv);
1904 if (tem < 0)
1905 {
1906 emacs_close (inchannel);
1907 emacs_close (forkout);
1908 report_file_error ("Creating pipe", Qnil);
1909 }
1910 outchannel = sv[1];
1911 forkin = sv[0];
1912 }
1913
1914 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
1915 {
1916 int tem;
1917
1918 tem = pipe (wait_child_setup);
1919 if (tem < 0)
1920 report_file_error ("Creating pipe", Qnil);
1921 tem = fcntl (wait_child_setup[1], F_GETFD, 0);
1922 if (tem >= 0)
1923 tem = fcntl (wait_child_setup[1], F_SETFD, tem | FD_CLOEXEC);
1924 if (tem < 0)
1925 {
1926 emacs_close (wait_child_setup[0]);
1927 emacs_close (wait_child_setup[1]);
1928 report_file_error ("Setting file descriptor flags", Qnil);
1929 }
1930 }
1931 #endif
1932
1933 #if 0
1934 /* Replaced by close_process_descs */
1935 set_exclusive_use (inchannel);
1936 set_exclusive_use (outchannel);
1937 #endif
1938
1939 #ifdef O_NONBLOCK
1940 fcntl (inchannel, F_SETFL, O_NONBLOCK);
1941 fcntl (outchannel, F_SETFL, O_NONBLOCK);
1942 #else
1943 #ifdef O_NDELAY
1944 fcntl (inchannel, F_SETFL, O_NDELAY);
1945 fcntl (outchannel, F_SETFL, O_NDELAY);
1946 #endif
1947 #endif
1948
1949 /* Record this as an active process, with its channels.
1950 As a result, child_setup will close Emacs's side of the pipes. */
1951 chan_process[inchannel] = process;
1952 XPROCESS (process)->infd = inchannel;
1953 XPROCESS (process)->outfd = outchannel;
1954
1955 /* Previously we recorded the tty descriptor used in the subprocess.
1956 It was only used for getting the foreground tty process, so now
1957 we just reopen the device (see emacs_get_tty_pgrp) as this is
1958 more portable (see USG_SUBTTY_WORKS above). */
1959
1960 XPROCESS (process)->pty_flag = pty_flag;
1961 XPROCESS (process)->status = Qrun;
1962 setup_process_coding_systems (process);
1963
1964 /* Delay interrupts until we have a chance to store
1965 the new fork's pid in its process structure */
1966 #ifdef POSIX_SIGNALS
1967 sigemptyset (&blocked);
1968 #ifdef SIGCHLD
1969 sigaddset (&blocked, SIGCHLD);
1970 #endif
1971 #ifdef HAVE_WORKING_VFORK
1972 /* On many hosts (e.g. Solaris 2.4), if a vforked child calls `signal',
1973 this sets the parent's signal handlers as well as the child's.
1974 So delay all interrupts whose handlers the child might munge,
1975 and record the current handlers so they can be restored later. */
1976 sigaddset (&blocked, SIGINT ); sigaction (SIGINT , 0, &sigint_action );
1977 sigaddset (&blocked, SIGQUIT); sigaction (SIGQUIT, 0, &sigquit_action);
1978 #ifdef AIX
1979 sigaddset (&blocked, SIGHUP ); sigaction (SIGHUP , 0, &sighup_action );
1980 #endif
1981 #endif /* HAVE_WORKING_VFORK */
1982 sigprocmask (SIG_BLOCK, &blocked, &procmask);
1983 #else /* !POSIX_SIGNALS */
1984 #ifdef SIGCHLD
1985 #if defined (BSD_SYSTEM) || defined (HPUX)
1986 sigsetmask (sigmask (SIGCHLD));
1987 #else /* ordinary USG */
1988 #if 0
1989 sigchld_deferred = 0;
1990 sigchld = signal (SIGCHLD, create_process_sigchld);
1991 #endif
1992 #endif /* ordinary USG */
1993 #endif /* SIGCHLD */
1994 #endif /* !POSIX_SIGNALS */
1995
1996 FD_SET (inchannel, &input_wait_mask);
1997 FD_SET (inchannel, &non_keyboard_wait_mask);
1998 if (inchannel > max_process_desc)
1999 max_process_desc = inchannel;
2000
2001 /* Until we store the proper pid, enable sigchld_handler
2002 to recognize an unknown pid as standing for this process.
2003 It is very important not to let this `marker' value stay
2004 in the table after this function has returned; if it does
2005 it might cause call-process to hang and subsequent asynchronous
2006 processes to get their return values scrambled. */
2007 XPROCESS (process)->pid = -1;
2008
2009 BLOCK_INPUT;
2010
2011 {
2012 /* child_setup must clobber environ on systems with true vfork.
2013 Protect it from permanent change. */
2014 char **save_environ = environ;
2015
2016 current_dir = ENCODE_FILE (current_dir);
2017
2018 #ifndef WINDOWSNT
2019 pid = vfork ();
2020 if (pid == 0)
2021 #endif /* not WINDOWSNT */
2022 {
2023 int xforkin = forkin;
2024 int xforkout = forkout;
2025
2026 #if 0 /* This was probably a mistake--it duplicates code later on,
2027 but fails to handle all the cases. */
2028 /* Make sure SIGCHLD is not blocked in the child. */
2029 sigsetmask (SIGEMPTYMASK);
2030 #endif
2031
2032 /* Make the pty be the controlling terminal of the process. */
2033 #ifdef HAVE_PTYS
2034 /* First, disconnect its current controlling terminal. */
2035 #ifdef HAVE_SETSID
2036 /* We tried doing setsid only if pty_flag, but it caused
2037 process_set_signal to fail on SGI when using a pipe. */
2038 setsid ();
2039 /* Make the pty's terminal the controlling terminal. */
2040 if (pty_flag)
2041 {
2042 #ifdef TIOCSCTTY
2043 /* We ignore the return value
2044 because faith@cs.unc.edu says that is necessary on Linux. */
2045 ioctl (xforkin, TIOCSCTTY, 0);
2046 #endif
2047 }
2048 #else /* not HAVE_SETSID */
2049 #ifdef USG
2050 /* It's very important to call setpgrp here and no time
2051 afterwards. Otherwise, we lose our controlling tty which
2052 is set when we open the pty. */
2053 setpgrp ();
2054 #endif /* USG */
2055 #endif /* not HAVE_SETSID */
2056 #if defined (HAVE_TERMIOS) && defined (LDISC1)
2057 if (pty_flag && xforkin >= 0)
2058 {
2059 struct termios t;
2060 tcgetattr (xforkin, &t);
2061 t.c_lflag = LDISC1;
2062 if (tcsetattr (xforkin, TCSANOW, &t) < 0)
2063 emacs_write (1, "create_process/tcsetattr LDISC1 failed\n", 39);
2064 }
2065 #else
2066 #if defined (NTTYDISC) && defined (TIOCSETD)
2067 if (pty_flag && xforkin >= 0)
2068 {
2069 /* Use new line discipline. */
2070 int ldisc = NTTYDISC;
2071 ioctl (xforkin, TIOCSETD, &ldisc);
2072 }
2073 #endif
2074 #endif
2075 #ifdef TIOCNOTTY
2076 /* In 4.3BSD, the TIOCSPGRP bug has been fixed, and now you
2077 can do TIOCSPGRP only to the process's controlling tty. */
2078 if (pty_flag)
2079 {
2080 /* I wonder: would just ioctl (0, TIOCNOTTY, 0) work here?
2081 I can't test it since I don't have 4.3. */
2082 int j = emacs_open ("/dev/tty", O_RDWR, 0);
2083 ioctl (j, TIOCNOTTY, 0);
2084 emacs_close (j);
2085 #ifndef USG
2086 /* In order to get a controlling terminal on some versions
2087 of BSD, it is necessary to put the process in pgrp 0
2088 before it opens the terminal. */
2089 #ifdef HAVE_SETPGID
2090 setpgid (0, 0);
2091 #else
2092 setpgrp (0, 0);
2093 #endif
2094 #endif
2095 }
2096 #endif /* TIOCNOTTY */
2097
2098 #if !defined (DONT_REOPEN_PTY)
2099 /*** There is a suggestion that this ought to be a
2100 conditional on TIOCSPGRP,
2101 or !(defined (HAVE_SETSID) && defined (TIOCSCTTY)).
2102 Trying the latter gave the wrong results on Debian GNU/Linux 1.1;
2103 that system does seem to need this code, even though
2104 both HAVE_SETSID and TIOCSCTTY are defined. */
2105 /* Now close the pty (if we had it open) and reopen it.
2106 This makes the pty the controlling terminal of the subprocess. */
2107 if (pty_flag)
2108 {
2109
2110 /* I wonder if emacs_close (emacs_open (pty_name, ...))
2111 would work? */
2112 if (xforkin >= 0)
2113 emacs_close (xforkin);
2114 xforkout = xforkin = emacs_open (pty_name, O_RDWR, 0);
2115
2116 if (xforkin < 0)
2117 {
2118 emacs_write (1, "Couldn't open the pty terminal ", 31);
2119 emacs_write (1, pty_name, strlen (pty_name));
2120 emacs_write (1, "\n", 1);
2121 _exit (1);
2122 }
2123
2124 }
2125 #endif /* not DONT_REOPEN_PTY */
2126
2127 #ifdef SETUP_SLAVE_PTY
2128 if (pty_flag)
2129 {
2130 SETUP_SLAVE_PTY;
2131 }
2132 #endif /* SETUP_SLAVE_PTY */
2133 #ifdef AIX
2134 /* On AIX, we've disabled SIGHUP above once we start a child on a pty.
2135 Now reenable it in the child, so it will die when we want it to. */
2136 if (pty_flag)
2137 signal (SIGHUP, SIG_DFL);
2138 #endif
2139 #endif /* HAVE_PTYS */
2140
2141 signal (SIGINT, SIG_DFL);
2142 signal (SIGQUIT, SIG_DFL);
2143
2144 /* Stop blocking signals in the child. */
2145 #ifdef POSIX_SIGNALS
2146 sigprocmask (SIG_SETMASK, &procmask, 0);
2147 #else /* !POSIX_SIGNALS */
2148 #ifdef SIGCHLD
2149 #if defined (BSD_SYSTEM) || defined (HPUX)
2150 sigsetmask (SIGEMPTYMASK);
2151 #else /* ordinary USG */
2152 #if 0
2153 signal (SIGCHLD, sigchld);
2154 #endif
2155 #endif /* ordinary USG */
2156 #endif /* SIGCHLD */
2157 #endif /* !POSIX_SIGNALS */
2158
2159 if (pty_flag)
2160 child_setup_tty (xforkout);
2161 #ifdef WINDOWSNT
2162 pid = child_setup (xforkin, xforkout, xforkout,
2163 new_argv, 1, current_dir);
2164 #else /* not WINDOWSNT */
2165 #ifdef FD_CLOEXEC
2166 emacs_close (wait_child_setup[0]);
2167 #endif
2168 child_setup (xforkin, xforkout, xforkout,
2169 new_argv, 1, current_dir);
2170 #endif /* not WINDOWSNT */
2171 }
2172 environ = save_environ;
2173 }
2174
2175 UNBLOCK_INPUT;
2176
2177 /* This runs in the Emacs process. */
2178 if (pid < 0)
2179 {
2180 if (forkin >= 0)
2181 emacs_close (forkin);
2182 if (forkin != forkout && forkout >= 0)
2183 emacs_close (forkout);
2184 }
2185 else
2186 {
2187 /* vfork succeeded. */
2188 XPROCESS (process)->pid = pid;
2189
2190 #ifdef WINDOWSNT
2191 register_child (pid, inchannel);
2192 #endif /* WINDOWSNT */
2193
2194 /* If the subfork execv fails, and it exits,
2195 this close hangs. I don't know why.
2196 So have an interrupt jar it loose. */
2197 {
2198 struct atimer *timer;
2199 EMACS_TIME offset;
2200
2201 stop_polling ();
2202 EMACS_SET_SECS_USECS (offset, 1, 0);
2203 timer = start_atimer (ATIMER_RELATIVE, offset, create_process_1, 0);
2204
2205 if (forkin >= 0)
2206 emacs_close (forkin);
2207
2208 cancel_atimer (timer);
2209 start_polling ();
2210 }
2211
2212 if (forkin != forkout && forkout >= 0)
2213 emacs_close (forkout);
2214
2215 #ifdef HAVE_PTYS
2216 if (pty_flag)
2217 XPROCESS (process)->tty_name = build_string (pty_name);
2218 else
2219 #endif
2220 XPROCESS (process)->tty_name = Qnil;
2221
2222 #if !defined (WINDOWSNT) && defined (FD_CLOEXEC)
2223 /* Wait for child_setup to complete in case that vfork is
2224 actually defined as fork. The descriptor wait_child_setup[1]
2225 of a pipe is closed at the child side either by close-on-exec
2226 on successful execvp or the _exit call in child_setup. */
2227 {
2228 char dummy;
2229
2230 emacs_close (wait_child_setup[1]);
2231 emacs_read (wait_child_setup[0], &dummy, 1);
2232 emacs_close (wait_child_setup[0]);
2233 }
2234 #endif
2235 }
2236
2237 /* Restore the signal state whether vfork succeeded or not.
2238 (We will signal an error, below, if it failed.) */
2239 #ifdef POSIX_SIGNALS
2240 #ifdef HAVE_WORKING_VFORK
2241 /* Restore the parent's signal handlers. */
2242 sigaction (SIGINT, &sigint_action, 0);
2243 sigaction (SIGQUIT, &sigquit_action, 0);
2244 #ifdef AIX
2245 sigaction (SIGHUP, &sighup_action, 0);
2246 #endif
2247 #endif /* HAVE_WORKING_VFORK */
2248 /* Stop blocking signals in the parent. */
2249 sigprocmask (SIG_SETMASK, &procmask, 0);
2250 #else /* !POSIX_SIGNALS */
2251 #ifdef SIGCHLD
2252 #if defined (BSD_SYSTEM) || defined (HPUX)
2253 sigsetmask (SIGEMPTYMASK);
2254 #else /* ordinary USG */
2255 #if 0
2256 signal (SIGCHLD, sigchld);
2257 /* Now really handle any of these signals
2258 that came in during this function. */
2259 if (sigchld_deferred)
2260 kill (getpid (), SIGCHLD);
2261 #endif
2262 #endif /* ordinary USG */
2263 #endif /* SIGCHLD */
2264 #endif /* !POSIX_SIGNALS */
2265
2266 /* Now generate the error if vfork failed. */
2267 if (pid < 0)
2268 report_file_error ("Doing vfork", Qnil);
2269 }
2270
2271 \f
2272 #ifdef HAVE_SOCKETS
2273
2274 /* Convert an internal struct sockaddr to a lisp object (vector or string).
2275 The address family of sa is not included in the result. */
2276
2277 static Lisp_Object
2278 conv_sockaddr_to_lisp (sa, len)
2279 struct sockaddr *sa;
2280 int len;
2281 {
2282 Lisp_Object address;
2283 int i;
2284 unsigned char *cp;
2285 register struct Lisp_Vector *p;
2286
2287 /* Workaround for a bug in getsockname on BSD: Names bound to
2288 sockets in the UNIX domain are inaccessible; getsockname returns
2289 a zero length name. */
2290 if (len < OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family))
2291 return empty_unibyte_string;
2292
2293 switch (sa->sa_family)
2294 {
2295 case AF_INET:
2296 {
2297 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2298 len = sizeof (sin->sin_addr) + 1;
2299 address = Fmake_vector (make_number (len), Qnil);
2300 p = XVECTOR (address);
2301 p->contents[--len] = make_number (ntohs (sin->sin_port));
2302 cp = (unsigned char *) &sin->sin_addr;
2303 break;
2304 }
2305 #ifdef AF_INET6
2306 case AF_INET6:
2307 {
2308 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2309 uint16_t *ip6 = (uint16_t *) &sin6->sin6_addr;
2310 len = sizeof (sin6->sin6_addr)/2 + 1;
2311 address = Fmake_vector (make_number (len), Qnil);
2312 p = XVECTOR (address);
2313 p->contents[--len] = make_number (ntohs (sin6->sin6_port));
2314 for (i = 0; i < len; i++)
2315 p->contents[i] = make_number (ntohs (ip6[i]));
2316 return address;
2317 }
2318 #endif
2319 #ifdef HAVE_LOCAL_SOCKETS
2320 case AF_LOCAL:
2321 {
2322 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2323 for (i = 0; i < sizeof (sockun->sun_path); i++)
2324 if (sockun->sun_path[i] == 0)
2325 break;
2326 return make_unibyte_string (sockun->sun_path, i);
2327 }
2328 #endif
2329 default:
2330 len -= OFFSETOF (struct sockaddr, sa_family) + sizeof (sa->sa_family);
2331 address = Fcons (make_number (sa->sa_family),
2332 Fmake_vector (make_number (len), Qnil));
2333 p = XVECTOR (XCDR (address));
2334 cp = (unsigned char *) &sa->sa_family + sizeof (sa->sa_family);
2335 break;
2336 }
2337
2338 i = 0;
2339 while (i < len)
2340 p->contents[i++] = make_number (*cp++);
2341
2342 return address;
2343 }
2344
2345
2346 /* Get family and required size for sockaddr structure to hold ADDRESS. */
2347
2348 static int
2349 get_lisp_to_sockaddr_size (address, familyp)
2350 Lisp_Object address;
2351 int *familyp;
2352 {
2353 register struct Lisp_Vector *p;
2354
2355 if (VECTORP (address))
2356 {
2357 p = XVECTOR (address);
2358 if (p->size == 5)
2359 {
2360 *familyp = AF_INET;
2361 return sizeof (struct sockaddr_in);
2362 }
2363 #ifdef AF_INET6
2364 else if (p->size == 9)
2365 {
2366 *familyp = AF_INET6;
2367 return sizeof (struct sockaddr_in6);
2368 }
2369 #endif
2370 }
2371 #ifdef HAVE_LOCAL_SOCKETS
2372 else if (STRINGP (address))
2373 {
2374 *familyp = AF_LOCAL;
2375 return sizeof (struct sockaddr_un);
2376 }
2377 #endif
2378 else if (CONSP (address) && INTEGERP (XCAR (address)) && VECTORP (XCDR (address)))
2379 {
2380 struct sockaddr *sa;
2381 *familyp = XINT (XCAR (address));
2382 p = XVECTOR (XCDR (address));
2383 return p->size + sizeof (sa->sa_family);
2384 }
2385 return 0;
2386 }
2387
2388 /* Convert an address object (vector or string) to an internal sockaddr.
2389
2390 The address format has been basically validated by
2391 get_lisp_to_sockaddr_size, but this does not mean FAMILY is valid;
2392 it could have come from user data. So if FAMILY is not valid,
2393 we return after zeroing *SA. */
2394
2395 static void
2396 conv_lisp_to_sockaddr (family, address, sa, len)
2397 int family;
2398 Lisp_Object address;
2399 struct sockaddr *sa;
2400 int len;
2401 {
2402 register struct Lisp_Vector *p;
2403 register unsigned char *cp = NULL;
2404 register int i;
2405
2406 bzero (sa, len);
2407
2408 if (VECTORP (address))
2409 {
2410 p = XVECTOR (address);
2411 if (family == AF_INET)
2412 {
2413 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
2414 len = sizeof (sin->sin_addr) + 1;
2415 i = XINT (p->contents[--len]);
2416 sin->sin_port = htons (i);
2417 cp = (unsigned char *)&sin->sin_addr;
2418 sa->sa_family = family;
2419 }
2420 #ifdef AF_INET6
2421 else if (family == AF_INET6)
2422 {
2423 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
2424 uint16_t *ip6 = (uint16_t *)&sin6->sin6_addr;
2425 len = sizeof (sin6->sin6_addr) + 1;
2426 i = XINT (p->contents[--len]);
2427 sin6->sin6_port = htons (i);
2428 for (i = 0; i < len; i++)
2429 if (INTEGERP (p->contents[i]))
2430 {
2431 int j = XFASTINT (p->contents[i]) & 0xffff;
2432 ip6[i] = ntohs (j);
2433 }
2434 sa->sa_family = family;
2435 }
2436 #endif
2437 return;
2438 }
2439 else if (STRINGP (address))
2440 {
2441 #ifdef HAVE_LOCAL_SOCKETS
2442 if (family == AF_LOCAL)
2443 {
2444 struct sockaddr_un *sockun = (struct sockaddr_un *) sa;
2445 cp = SDATA (address);
2446 for (i = 0; i < sizeof (sockun->sun_path) && *cp; i++)
2447 sockun->sun_path[i] = *cp++;
2448 sa->sa_family = family;
2449 }
2450 #endif
2451 return;
2452 }
2453 else
2454 {
2455 p = XVECTOR (XCDR (address));
2456 cp = (unsigned char *)sa + sizeof (sa->sa_family);
2457 }
2458
2459 for (i = 0; i < len; i++)
2460 if (INTEGERP (p->contents[i]))
2461 *cp++ = XFASTINT (p->contents[i]) & 0xff;
2462 }
2463
2464 #ifdef DATAGRAM_SOCKETS
2465 DEFUN ("process-datagram-address", Fprocess_datagram_address, Sprocess_datagram_address,
2466 1, 1, 0,
2467 doc: /* Get the current datagram address associated with PROCESS. */)
2468 (process)
2469 Lisp_Object process;
2470 {
2471 int channel;
2472
2473 CHECK_PROCESS (process);
2474
2475 if (!DATAGRAM_CONN_P (process))
2476 return Qnil;
2477
2478 channel = XPROCESS (process)->infd;
2479 return conv_sockaddr_to_lisp (datagram_address[channel].sa,
2480 datagram_address[channel].len);
2481 }
2482
2483 DEFUN ("set-process-datagram-address", Fset_process_datagram_address, Sset_process_datagram_address,
2484 2, 2, 0,
2485 doc: /* Set the datagram address for PROCESS to ADDRESS.
2486 Returns nil upon error setting address, ADDRESS otherwise. */)
2487 (process, address)
2488 Lisp_Object process, address;
2489 {
2490 int channel;
2491 int family, len;
2492
2493 CHECK_PROCESS (process);
2494
2495 if (!DATAGRAM_CONN_P (process))
2496 return Qnil;
2497
2498 channel = XPROCESS (process)->infd;
2499
2500 len = get_lisp_to_sockaddr_size (address, &family);
2501 if (datagram_address[channel].len != len)
2502 return Qnil;
2503 conv_lisp_to_sockaddr (family, address, datagram_address[channel].sa, len);
2504 return address;
2505 }
2506 #endif
2507 \f
2508
2509 static struct socket_options {
2510 /* The name of this option. Should be lowercase version of option
2511 name without SO_ prefix. */
2512 char *name;
2513 /* Option level SOL_... */
2514 int optlevel;
2515 /* Option number SO_... */
2516 int optnum;
2517 enum { SOPT_UNKNOWN, SOPT_BOOL, SOPT_INT, SOPT_IFNAME, SOPT_LINGER } opttype;
2518 enum { OPIX_NONE=0, OPIX_MISC=1, OPIX_REUSEADDR=2 } optbit;
2519 } socket_options[] =
2520 {
2521 #ifdef SO_BINDTODEVICE
2522 { ":bindtodevice", SOL_SOCKET, SO_BINDTODEVICE, SOPT_IFNAME, OPIX_MISC },
2523 #endif
2524 #ifdef SO_BROADCAST
2525 { ":broadcast", SOL_SOCKET, SO_BROADCAST, SOPT_BOOL, OPIX_MISC },
2526 #endif
2527 #ifdef SO_DONTROUTE
2528 { ":dontroute", SOL_SOCKET, SO_DONTROUTE, SOPT_BOOL, OPIX_MISC },
2529 #endif
2530 #ifdef SO_KEEPALIVE
2531 { ":keepalive", SOL_SOCKET, SO_KEEPALIVE, SOPT_BOOL, OPIX_MISC },
2532 #endif
2533 #ifdef SO_LINGER
2534 { ":linger", SOL_SOCKET, SO_LINGER, SOPT_LINGER, OPIX_MISC },
2535 #endif
2536 #ifdef SO_OOBINLINE
2537 { ":oobinline", SOL_SOCKET, SO_OOBINLINE, SOPT_BOOL, OPIX_MISC },
2538 #endif
2539 #ifdef SO_PRIORITY
2540 { ":priority", SOL_SOCKET, SO_PRIORITY, SOPT_INT, OPIX_MISC },
2541 #endif
2542 #ifdef SO_REUSEADDR
2543 { ":reuseaddr", SOL_SOCKET, SO_REUSEADDR, SOPT_BOOL, OPIX_REUSEADDR },
2544 #endif
2545 { 0, 0, 0, SOPT_UNKNOWN, OPIX_NONE }
2546 };
2547
2548 /* Set option OPT to value VAL on socket S.
2549
2550 Returns (1<<socket_options[OPT].optbit) if option is known, 0 otherwise.
2551 Signals an error if setting a known option fails.
2552 */
2553
2554 static int
2555 set_socket_option (s, opt, val)
2556 int s;
2557 Lisp_Object opt, val;
2558 {
2559 char *name;
2560 struct socket_options *sopt;
2561 int ret = 0;
2562
2563 CHECK_SYMBOL (opt);
2564
2565 name = (char *) SDATA (SYMBOL_NAME (opt));
2566 for (sopt = socket_options; sopt->name; sopt++)
2567 if (strcmp (name, sopt->name) == 0)
2568 break;
2569
2570 switch (sopt->opttype)
2571 {
2572 case SOPT_BOOL:
2573 {
2574 int optval;
2575 optval = NILP (val) ? 0 : 1;
2576 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2577 &optval, sizeof (optval));
2578 break;
2579 }
2580
2581 case SOPT_INT:
2582 {
2583 int optval;
2584 if (INTEGERP (val))
2585 optval = XINT (val);
2586 else
2587 error ("Bad option value for %s", name);
2588 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2589 &optval, sizeof (optval));
2590 break;
2591 }
2592
2593 #ifdef SO_BINDTODEVICE
2594 case SOPT_IFNAME:
2595 {
2596 char devname[IFNAMSIZ+1];
2597
2598 /* This is broken, at least in the Linux 2.4 kernel.
2599 To unbind, the arg must be a zero integer, not the empty string.
2600 This should work on all systems. KFS. 2003-09-23. */
2601 bzero (devname, sizeof devname);
2602 if (STRINGP (val))
2603 {
2604 char *arg = (char *) SDATA (val);
2605 int len = min (strlen (arg), IFNAMSIZ);
2606 bcopy (arg, devname, len);
2607 }
2608 else if (!NILP (val))
2609 error ("Bad option value for %s", name);
2610 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2611 devname, IFNAMSIZ);
2612 break;
2613 }
2614 #endif
2615
2616 #ifdef SO_LINGER
2617 case SOPT_LINGER:
2618 {
2619 struct linger linger;
2620
2621 linger.l_onoff = 1;
2622 linger.l_linger = 0;
2623 if (INTEGERP (val))
2624 linger.l_linger = XINT (val);
2625 else
2626 linger.l_onoff = NILP (val) ? 0 : 1;
2627 ret = setsockopt (s, sopt->optlevel, sopt->optnum,
2628 &linger, sizeof (linger));
2629 break;
2630 }
2631 #endif
2632
2633 default:
2634 return 0;
2635 }
2636
2637 if (ret < 0)
2638 report_file_error ("Cannot set network option",
2639 Fcons (opt, Fcons (val, Qnil)));
2640 return (1 << sopt->optbit);
2641 }
2642
2643
2644 DEFUN ("set-network-process-option",
2645 Fset_network_process_option, Sset_network_process_option,
2646 3, 4, 0,
2647 doc: /* For network process PROCESS set option OPTION to value VALUE.
2648 See `make-network-process' for a list of options and values.
2649 If optional fourth arg NO-ERROR is non-nil, don't signal an error if
2650 OPTION is not a supported option, return nil instead; otherwise return t. */)
2651 (process, option, value, no_error)
2652 Lisp_Object process, option, value;
2653 Lisp_Object no_error;
2654 {
2655 int s;
2656 struct Lisp_Process *p;
2657
2658 CHECK_PROCESS (process);
2659 p = XPROCESS (process);
2660 if (!NETCONN1_P (p))
2661 error ("Process is not a network process");
2662
2663 s = p->infd;
2664 if (s < 0)
2665 error ("Process is not running");
2666
2667 if (set_socket_option (s, option, value))
2668 {
2669 p->childp = Fplist_put (p->childp, option, value);
2670 return Qt;
2671 }
2672
2673 if (NILP (no_error))
2674 error ("Unknown or unsupported option");
2675
2676 return Qnil;
2677 }
2678
2679 \f
2680 #ifdef HAVE_SERIAL
2681 DEFUN ("serial-process-configure",
2682 Fserial_process_configure,
2683 Sserial_process_configure,
2684 0, MANY, 0,
2685 doc: /* Configure speed, bytesize, etc. of a serial process.
2686
2687 Arguments are specified as keyword/argument pairs. Attributes that
2688 are not given are re-initialized from the process's current
2689 configuration (available via the function `process-contact') or set to
2690 reasonable default values. The following arguments are defined:
2691
2692 :process PROCESS
2693 :name NAME
2694 :buffer BUFFER
2695 :port PORT
2696 -- Any of these arguments can be given to identify the process that is
2697 to be configured. If none of these arguments is given, the current
2698 buffer's process is used.
2699
2700 :speed SPEED -- SPEED is the speed of the serial port in bits per
2701 second, also called baud rate. Any value can be given for SPEED, but
2702 most serial ports work only at a few defined values between 1200 and
2703 115200, with 9600 being the most common value. If SPEED is nil, the
2704 serial port is not configured any further, i.e., all other arguments
2705 are ignored. This may be useful for special serial ports such as
2706 Bluetooth-to-serial converters which can only be configured through AT
2707 commands. A value of nil for SPEED can be used only when passed
2708 through `make-serial-process' or `serial-term'.
2709
2710 :bytesize BYTESIZE -- BYTESIZE is the number of bits per byte, which
2711 can be 7 or 8. If BYTESIZE is not given or nil, a value of 8 is used.
2712
2713 :parity PARITY -- PARITY can be nil (don't use parity), the symbol
2714 `odd' (use odd parity), or the symbol `even' (use even parity). If
2715 PARITY is not given, no parity is used.
2716
2717 :stopbits STOPBITS -- STOPBITS is the number of stopbits used to
2718 terminate a byte transmission. STOPBITS can be 1 or 2. If STOPBITS
2719 is not given or nil, 1 stopbit is used.
2720
2721 :flowcontrol FLOWCONTROL -- FLOWCONTROL determines the type of
2722 flowcontrol to be used, which is either nil (don't use flowcontrol),
2723 the symbol `hw' (use RTS/CTS hardware flowcontrol), or the symbol `sw'
2724 \(use XON/XOFF software flowcontrol). If FLOWCONTROL is not given, no
2725 flowcontrol is used.
2726
2727 `serial-process-configure' is called by `make-serial-process' for the
2728 initial configuration of the serial port.
2729
2730 Examples:
2731
2732 \(serial-process-configure :process "/dev/ttyS0" :speed 1200)
2733
2734 \(serial-process-configure
2735 :buffer "COM1" :stopbits 1 :parity 'odd :flowcontrol 'hw)
2736
2737 \(serial-process-configure :port "\\\\.\\COM13" :bytesize 7)
2738
2739 usage: (serial-process-configure &rest ARGS) */)
2740 (nargs, args)
2741 int nargs;
2742 Lisp_Object *args;
2743 {
2744 struct Lisp_Process *p;
2745 Lisp_Object contact = Qnil;
2746 Lisp_Object proc = Qnil;
2747 struct gcpro gcpro1;
2748
2749 contact = Flist (nargs, args);
2750 GCPRO1 (contact);
2751
2752 proc = Fplist_get (contact, QCprocess);
2753 if (NILP (proc))
2754 proc = Fplist_get (contact, QCname);
2755 if (NILP (proc))
2756 proc = Fplist_get (contact, QCbuffer);
2757 if (NILP (proc))
2758 proc = Fplist_get (contact, QCport);
2759 proc = get_process (proc);
2760 p = XPROCESS (proc);
2761 if (!EQ (p->type, Qserial))
2762 error ("Not a serial process");
2763
2764 if (NILP (Fplist_get (p->childp, QCspeed)))
2765 {
2766 UNGCPRO;
2767 return Qnil;
2768 }
2769
2770 serial_configure (p, contact);
2771
2772 UNGCPRO;
2773 return Qnil;
2774 }
2775
2776 /* Used by make-serial-process to recover from errors. */
2777 Lisp_Object make_serial_process_unwind (Lisp_Object proc)
2778 {
2779 if (!PROCESSP (proc))
2780 abort ();
2781 remove_process (proc);
2782 return Qnil;
2783 }
2784
2785 DEFUN ("make-serial-process", Fmake_serial_process, Smake_serial_process,
2786 0, MANY, 0,
2787 doc: /* Create and return a serial port process.
2788
2789 In Emacs, serial port connections are represented by process objects,
2790 so input and output work as for subprocesses, and `delete-process'
2791 closes a serial port connection. However, a serial process has no
2792 process id, it cannot be signaled, and the status codes are different
2793 from normal processes.
2794
2795 `make-serial-process' creates a process and a buffer, on which you
2796 probably want to use `process-send-string'. Try \\[serial-term] for
2797 an interactive terminal. See below for examples.
2798
2799 Arguments are specified as keyword/argument pairs. The following
2800 arguments are defined:
2801
2802 :port PORT -- (mandatory) PORT is the path or name of the serial port.
2803 For example, this could be "/dev/ttyS0" on Unix. On Windows, this
2804 could be "COM1", or "\\\\.\\COM10" for ports higher than COM9 (double
2805 the backslashes in strings).
2806
2807 :speed SPEED -- (mandatory) is handled by `serial-process-configure',
2808 which is called by `make-serial-process'.
2809
2810 :name NAME -- NAME is the name of the process. If NAME is not given,
2811 the value of PORT is used.
2812
2813 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
2814 with the process. Process output goes at the end of that buffer,
2815 unless you specify an output stream or filter function to handle the
2816 output. If BUFFER is not given, the value of NAME is used.
2817
2818 :coding CODING -- If CODING is a symbol, it specifies the coding
2819 system used for both reading and writing for this process. If CODING
2820 is a cons (DECODING . ENCODING), DECODING is used for reading, and
2821 ENCODING is used for writing.
2822
2823 :noquery BOOL -- When exiting Emacs, query the user if BOOL is nil and
2824 the process is running. If BOOL is not given, query before exiting.
2825
2826 :stop BOOL -- Start process in the `stopped' state if BOOL is non-nil.
2827 In the stopped state, a serial process does not accept incoming data,
2828 but you can send outgoing data. The stopped state is cleared by
2829 `continue-process' and set by `stop-process'.
2830
2831 :filter FILTER -- Install FILTER as the process filter.
2832
2833 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
2834
2835 :plist PLIST -- Install PLIST as the initial plist of the process.
2836
2837 :speed
2838 :bytesize
2839 :parity
2840 :stopbits
2841 :flowcontrol
2842 -- These arguments are handled by `serial-process-configure', which is
2843 called by `make-serial-process'.
2844
2845 The original argument list, possibly modified by later configuration,
2846 is available via the function `process-contact'.
2847
2848 Examples:
2849
2850 \(make-serial-process :port "/dev/ttyS0" :speed 9600)
2851
2852 \(make-serial-process :port "COM1" :speed 115200 :stopbits 2)
2853
2854 \(make-serial-process :port "\\\\.\\COM13" :speed 1200 :bytesize 7 :parity 'odd)
2855
2856 \(make-serial-process :port "/dev/tty.BlueConsole-SPP-1" :speed nil)
2857
2858 usage: (make-serial-process &rest ARGS) */)
2859 (nargs, args)
2860 int nargs;
2861 Lisp_Object *args;
2862 {
2863 int fd = -1;
2864 Lisp_Object proc, contact, port;
2865 struct Lisp_Process *p;
2866 struct gcpro gcpro1;
2867 Lisp_Object name, buffer;
2868 Lisp_Object tem, val;
2869 int specpdl_count = -1;
2870
2871 if (nargs == 0)
2872 return Qnil;
2873
2874 contact = Flist (nargs, args);
2875 GCPRO1 (contact);
2876
2877 port = Fplist_get (contact, QCport);
2878 if (NILP (port))
2879 error ("No port specified");
2880 CHECK_STRING (port);
2881
2882 if (NILP (Fplist_member (contact, QCspeed)))
2883 error (":speed not specified");
2884 if (!NILP (Fplist_get (contact, QCspeed)))
2885 CHECK_NUMBER (Fplist_get (contact, QCspeed));
2886
2887 name = Fplist_get (contact, QCname);
2888 if (NILP (name))
2889 name = port;
2890 CHECK_STRING (name);
2891 proc = make_process (name);
2892 specpdl_count = SPECPDL_INDEX ();
2893 record_unwind_protect (make_serial_process_unwind, proc);
2894 p = XPROCESS (proc);
2895
2896 fd = serial_open ((char*) SDATA (port));
2897 p->infd = fd;
2898 p->outfd = fd;
2899 if (fd > max_process_desc)
2900 max_process_desc = fd;
2901 chan_process[fd] = proc;
2902
2903 buffer = Fplist_get (contact, QCbuffer);
2904 if (NILP (buffer))
2905 buffer = name;
2906 buffer = Fget_buffer_create (buffer);
2907 p->buffer = buffer;
2908
2909 p->childp = contact;
2910 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
2911 p->type = Qserial;
2912 p->sentinel = Fplist_get (contact, QCsentinel);
2913 p->filter = Fplist_get (contact, QCfilter);
2914 p->log = Qnil;
2915 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
2916 p->kill_without_query = 1;
2917 if (tem = Fplist_get (contact, QCstop), !NILP (tem))
2918 p->command = Qt;
2919 p->pty_flag = 0;
2920
2921 if (!EQ (p->command, Qt))
2922 {
2923 FD_SET (fd, &input_wait_mask);
2924 FD_SET (fd, &non_keyboard_wait_mask);
2925 }
2926
2927 if (BUFFERP (buffer))
2928 {
2929 set_marker_both (p->mark, buffer,
2930 BUF_ZV (XBUFFER (buffer)),
2931 BUF_ZV_BYTE (XBUFFER (buffer)));
2932 }
2933
2934 tem = Fplist_member (contact, QCcoding);
2935 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
2936 tem = Qnil;
2937
2938 val = Qnil;
2939 if (!NILP (tem))
2940 {
2941 val = XCAR (XCDR (tem));
2942 if (CONSP (val))
2943 val = XCAR (val);
2944 }
2945 else if (!NILP (Vcoding_system_for_read))
2946 val = Vcoding_system_for_read;
2947 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2948 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2949 val = Qnil;
2950 p->decode_coding_system = val;
2951
2952 val = Qnil;
2953 if (!NILP (tem))
2954 {
2955 val = XCAR (XCDR (tem));
2956 if (CONSP (val))
2957 val = XCDR (val);
2958 }
2959 else if (!NILP (Vcoding_system_for_write))
2960 val = Vcoding_system_for_write;
2961 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
2962 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
2963 val = Qnil;
2964 p->encode_coding_system = val;
2965
2966 setup_process_coding_systems (proc);
2967 p->decoding_buf = make_uninit_string (0);
2968 p->decoding_carryover = 0;
2969 p->encoding_buf = make_uninit_string (0);
2970 p->inherit_coding_system_flag
2971 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
2972
2973 Fserial_process_configure(nargs, args);
2974
2975 specpdl_ptr = specpdl + specpdl_count;
2976
2977 UNGCPRO;
2978 return proc;
2979 }
2980 #endif /* HAVE_SERIAL */
2981
2982 /* Create a network stream/datagram client/server process. Treated
2983 exactly like a normal process when reading and writing. Primary
2984 differences are in status display and process deletion. A network
2985 connection has no PID; you cannot signal it. All you can do is
2986 stop/continue it and deactivate/close it via delete-process */
2987
2988 DEFUN ("make-network-process", Fmake_network_process, Smake_network_process,
2989 0, MANY, 0,
2990 doc: /* Create and return a network server or client process.
2991
2992 In Emacs, network connections are represented by process objects, so
2993 input and output work as for subprocesses and `delete-process' closes
2994 a network connection. However, a network process has no process id,
2995 it cannot be signaled, and the status codes are different from normal
2996 processes.
2997
2998 Arguments are specified as keyword/argument pairs. The following
2999 arguments are defined:
3000
3001 :name NAME -- NAME is name for process. It is modified if necessary
3002 to make it unique.
3003
3004 :buffer BUFFER -- BUFFER is the buffer (or buffer-name) to associate
3005 with the process. Process output goes at end of that buffer, unless
3006 you specify an output stream or filter function to handle the output.
3007 BUFFER may be also nil, meaning that this process is not associated
3008 with any buffer.
3009
3010 :host HOST -- HOST is name of the host to connect to, or its IP
3011 address. The symbol `local' specifies the local host. If specified
3012 for a server process, it must be a valid name or address for the local
3013 host, and only clients connecting to that address will be accepted.
3014
3015 :service SERVICE -- SERVICE is name of the service desired, or an
3016 integer specifying a port number to connect to. If SERVICE is t,
3017 a random port number is selected for the server. (If Emacs was
3018 compiled with getaddrinfo, a port number can also be specified as a
3019 string, e.g. "80", as well as an integer. This is not portable.)
3020
3021 :type TYPE -- TYPE is the type of connection. The default (nil) is a
3022 stream type connection, `datagram' creates a datagram type connection.
3023
3024 :family FAMILY -- FAMILY is the address (and protocol) family for the
3025 service specified by HOST and SERVICE. The default (nil) is to use
3026 whatever address family (IPv4 or IPv6) that is defined for the host
3027 and port number specified by HOST and SERVICE. Other address families
3028 supported are:
3029 local -- for a local (i.e. UNIX) address specified by SERVICE.
3030 ipv4 -- use IPv4 address family only.
3031 ipv6 -- use IPv6 address family only.
3032
3033 :local ADDRESS -- ADDRESS is the local address used for the connection.
3034 This parameter is ignored when opening a client process. When specified
3035 for a server process, the FAMILY, HOST and SERVICE args are ignored.
3036
3037 :remote ADDRESS -- ADDRESS is the remote partner's address for the
3038 connection. This parameter is ignored when opening a stream server
3039 process. For a datagram server process, it specifies the initial
3040 setting of the remote datagram address. When specified for a client
3041 process, the FAMILY, HOST, and SERVICE args are ignored.
3042
3043 The format of ADDRESS depends on the address family:
3044 - An IPv4 address is represented as an vector of integers [A B C D P]
3045 corresponding to numeric IP address A.B.C.D and port number P.
3046 - A local address is represented as a string with the address in the
3047 local address space.
3048 - An "unsupported family" address is represented by a cons (F . AV)
3049 where F is the family number and AV is a vector containing the socket
3050 address data with one element per address data byte. Do not rely on
3051 this format in portable code, as it may depend on implementation
3052 defined constants, data sizes, and data structure alignment.
3053
3054 :coding CODING -- If CODING is a symbol, it specifies the coding
3055 system used for both reading and writing for this process. If CODING
3056 is a cons (DECODING . ENCODING), DECODING is used for reading, and
3057 ENCODING is used for writing.
3058
3059 :nowait BOOL -- If BOOL is non-nil for a stream type client process,
3060 return without waiting for the connection to complete; instead, the
3061 sentinel function will be called with second arg matching "open" (if
3062 successful) or "failed" when the connect completes. Default is to use
3063 a blocking connect (i.e. wait) for stream type connections.
3064
3065 :noquery BOOL -- Query the user unless BOOL is non-nil, and process is
3066 running when Emacs is exited.
3067
3068 :stop BOOL -- Start process in the `stopped' state if BOOL non-nil.
3069 In the stopped state, a server process does not accept new
3070 connections, and a client process does not handle incoming traffic.
3071 The stopped state is cleared by `continue-process' and set by
3072 `stop-process'.
3073
3074 :filter FILTER -- Install FILTER as the process filter.
3075
3076 :filter-multibyte BOOL -- If BOOL is non-nil, strings given to the
3077 process filter are multibyte, otherwise they are unibyte.
3078 If this keyword is not specified, the strings are multibyte if
3079 `default-enable-multibyte-characters' is non-nil.
3080
3081 :sentinel SENTINEL -- Install SENTINEL as the process sentinel.
3082
3083 :log LOG -- Install LOG as the server process log function. This
3084 function is called when the server accepts a network connection from a
3085 client. The arguments are SERVER, CLIENT, and MESSAGE, where SERVER
3086 is the server process, CLIENT is the new process for the connection,
3087 and MESSAGE is a string.
3088
3089 :plist PLIST -- Install PLIST as the new process' initial plist.
3090
3091 :server QLEN -- if QLEN is non-nil, create a server process for the
3092 specified FAMILY, SERVICE, and connection type (stream or datagram).
3093 If QLEN is an integer, it is used as the max. length of the server's
3094 pending connection queue (also known as the backlog); the default
3095 queue length is 5. Default is to create a client process.
3096
3097 The following network options can be specified for this connection:
3098
3099 :broadcast BOOL -- Allow send and receive of datagram broadcasts.
3100 :dontroute BOOL -- Only send to directly connected hosts.
3101 :keepalive BOOL -- Send keep-alive messages on network stream.
3102 :linger BOOL or TIMEOUT -- Send queued messages before closing.
3103 :oobinline BOOL -- Place out-of-band data in receive data stream.
3104 :priority INT -- Set protocol defined priority for sent packets.
3105 :reuseaddr BOOL -- Allow reusing a recently used local address
3106 (this is allowed by default for a server process).
3107 :bindtodevice NAME -- bind to interface NAME. Using this may require
3108 special privileges on some systems.
3109
3110 Consult the relevant system programmer's manual pages for more
3111 information on using these options.
3112
3113
3114 A server process will listen for and accept connections from clients.
3115 When a client connection is accepted, a new network process is created
3116 for the connection with the following parameters:
3117
3118 - The client's process name is constructed by concatenating the server
3119 process' NAME and a client identification string.
3120 - If the FILTER argument is non-nil, the client process will not get a
3121 separate process buffer; otherwise, the client's process buffer is a newly
3122 created buffer named after the server process' BUFFER name or process
3123 NAME concatenated with the client identification string.
3124 - The connection type and the process filter and sentinel parameters are
3125 inherited from the server process' TYPE, FILTER and SENTINEL.
3126 - The client process' contact info is set according to the client's
3127 addressing information (typically an IP address and a port number).
3128 - The client process' plist is initialized from the server's plist.
3129
3130 Notice that the FILTER and SENTINEL args are never used directly by
3131 the server process. Also, the BUFFER argument is not used directly by
3132 the server process, but via the optional :log function, accepted (and
3133 failed) connections may be logged in the server process' buffer.
3134
3135 The original argument list, modified with the actual connection
3136 information, is available via the `process-contact' function.
3137
3138 usage: (make-network-process &rest ARGS) */)
3139 (nargs, args)
3140 int nargs;
3141 Lisp_Object *args;
3142 {
3143 Lisp_Object proc;
3144 Lisp_Object contact;
3145 struct Lisp_Process *p;
3146 #ifdef HAVE_GETADDRINFO
3147 struct addrinfo ai, *res, *lres;
3148 struct addrinfo hints;
3149 char *portstring, portbuf[128];
3150 #else /* HAVE_GETADDRINFO */
3151 struct _emacs_addrinfo
3152 {
3153 int ai_family;
3154 int ai_socktype;
3155 int ai_protocol;
3156 int ai_addrlen;
3157 struct sockaddr *ai_addr;
3158 struct _emacs_addrinfo *ai_next;
3159 } ai, *res, *lres;
3160 #endif /* HAVE_GETADDRINFO */
3161 struct sockaddr_in address_in;
3162 #ifdef HAVE_LOCAL_SOCKETS
3163 struct sockaddr_un address_un;
3164 #endif
3165 int port;
3166 int ret = 0;
3167 int xerrno = 0;
3168 int s = -1, outch, inch;
3169 struct gcpro gcpro1;
3170 int count = SPECPDL_INDEX ();
3171 int count1;
3172 Lisp_Object QCaddress; /* one of QClocal or QCremote */
3173 Lisp_Object tem;
3174 Lisp_Object name, buffer, host, service, address;
3175 Lisp_Object filter, sentinel;
3176 int is_non_blocking_client = 0;
3177 int is_server = 0, backlog = 5;
3178 int socktype;
3179 int family = -1;
3180
3181 if (nargs == 0)
3182 return Qnil;
3183
3184 /* Save arguments for process-contact and clone-process. */
3185 contact = Flist (nargs, args);
3186 GCPRO1 (contact);
3187
3188 #ifdef WINDOWSNT
3189 /* Ensure socket support is loaded if available. */
3190 init_winsock (TRUE);
3191 #endif
3192
3193 /* :type TYPE (nil: stream, datagram */
3194 tem = Fplist_get (contact, QCtype);
3195 if (NILP (tem))
3196 socktype = SOCK_STREAM;
3197 #ifdef DATAGRAM_SOCKETS
3198 else if (EQ (tem, Qdatagram))
3199 socktype = SOCK_DGRAM;
3200 #endif
3201 else
3202 error ("Unsupported connection type");
3203
3204 /* :server BOOL */
3205 tem = Fplist_get (contact, QCserver);
3206 if (!NILP (tem))
3207 {
3208 /* Don't support network sockets when non-blocking mode is
3209 not available, since a blocked Emacs is not useful. */
3210 #if !defined(O_NONBLOCK) && !defined(O_NDELAY)
3211 error ("Network servers not supported");
3212 #else
3213 is_server = 1;
3214 if (INTEGERP (tem))
3215 backlog = XINT (tem);
3216 #endif
3217 }
3218
3219 /* Make QCaddress an alias for :local (server) or :remote (client). */
3220 QCaddress = is_server ? QClocal : QCremote;
3221
3222 /* :nowait BOOL */
3223 if (!is_server && socktype == SOCK_STREAM
3224 && (tem = Fplist_get (contact, QCnowait), !NILP (tem)))
3225 {
3226 #ifndef NON_BLOCKING_CONNECT
3227 error ("Non-blocking connect not supported");
3228 #else
3229 is_non_blocking_client = 1;
3230 #endif
3231 }
3232
3233 name = Fplist_get (contact, QCname);
3234 buffer = Fplist_get (contact, QCbuffer);
3235 filter = Fplist_get (contact, QCfilter);
3236 sentinel = Fplist_get (contact, QCsentinel);
3237
3238 CHECK_STRING (name);
3239
3240 /* Initialize addrinfo structure in case we don't use getaddrinfo. */
3241 ai.ai_socktype = socktype;
3242 ai.ai_protocol = 0;
3243 ai.ai_next = NULL;
3244 res = &ai;
3245
3246 /* :local ADDRESS or :remote ADDRESS */
3247 address = Fplist_get (contact, QCaddress);
3248 if (!NILP (address))
3249 {
3250 host = service = Qnil;
3251
3252 if (!(ai.ai_addrlen = get_lisp_to_sockaddr_size (address, &family)))
3253 error ("Malformed :address");
3254 ai.ai_family = family;
3255 ai.ai_addr = alloca (ai.ai_addrlen);
3256 conv_lisp_to_sockaddr (family, address, ai.ai_addr, ai.ai_addrlen);
3257 goto open_socket;
3258 }
3259
3260 /* :family FAMILY -- nil (for Inet), local, or integer. */
3261 tem = Fplist_get (contact, QCfamily);
3262 if (NILP (tem))
3263 {
3264 #if defined(HAVE_GETADDRINFO) && defined(AF_INET6)
3265 family = AF_UNSPEC;
3266 #else
3267 family = AF_INET;
3268 #endif
3269 }
3270 #ifdef HAVE_LOCAL_SOCKETS
3271 else if (EQ (tem, Qlocal))
3272 family = AF_LOCAL;
3273 #endif
3274 #ifdef AF_INET6
3275 else if (EQ (tem, Qipv6))
3276 family = AF_INET6;
3277 #endif
3278 else if (EQ (tem, Qipv4))
3279 family = AF_INET;
3280 else if (INTEGERP (tem))
3281 family = XINT (tem);
3282 else
3283 error ("Unknown address family");
3284
3285 ai.ai_family = family;
3286
3287 /* :service SERVICE -- string, integer (port number), or t (random port). */
3288 service = Fplist_get (contact, QCservice);
3289
3290 #ifdef HAVE_LOCAL_SOCKETS
3291 if (family == AF_LOCAL)
3292 {
3293 /* Host is not used. */
3294 host = Qnil;
3295 CHECK_STRING (service);
3296 bzero (&address_un, sizeof address_un);
3297 address_un.sun_family = AF_LOCAL;
3298 strncpy (address_un.sun_path, SDATA (service), sizeof address_un.sun_path);
3299 ai.ai_addr = (struct sockaddr *) &address_un;
3300 ai.ai_addrlen = sizeof address_un;
3301 goto open_socket;
3302 }
3303 #endif
3304
3305 /* :host HOST -- hostname, ip address, or 'local for localhost. */
3306 host = Fplist_get (contact, QChost);
3307 if (!NILP (host))
3308 {
3309 if (EQ (host, Qlocal))
3310 host = build_string ("localhost");
3311 CHECK_STRING (host);
3312 }
3313
3314 /* Slow down polling to every ten seconds.
3315 Some kernels have a bug which causes retrying connect to fail
3316 after a connect. Polling can interfere with gethostbyname too. */
3317 #ifdef POLL_FOR_INPUT
3318 if (socktype == SOCK_STREAM)
3319 {
3320 record_unwind_protect (unwind_stop_other_atimers, Qnil);
3321 bind_polling_period (10);
3322 }
3323 #endif
3324
3325 #ifdef HAVE_GETADDRINFO
3326 /* If we have a host, use getaddrinfo to resolve both host and service.
3327 Otherwise, use getservbyname to lookup the service. */
3328 if (!NILP (host))
3329 {
3330
3331 /* SERVICE can either be a string or int.
3332 Convert to a C string for later use by getaddrinfo. */
3333 if (EQ (service, Qt))
3334 portstring = "0";
3335 else if (INTEGERP (service))
3336 {
3337 sprintf (portbuf, "%ld", (long) XINT (service));
3338 portstring = portbuf;
3339 }
3340 else
3341 {
3342 CHECK_STRING (service);
3343 portstring = SDATA (service);
3344 }
3345
3346 immediate_quit = 1;
3347 QUIT;
3348 memset (&hints, 0, sizeof (hints));
3349 hints.ai_flags = 0;
3350 hints.ai_family = family;
3351 hints.ai_socktype = socktype;
3352 hints.ai_protocol = 0;
3353
3354 #ifdef HAVE_RES_INIT
3355 res_init ();
3356 #endif
3357
3358 ret = getaddrinfo (SDATA (host), portstring, &hints, &res);
3359 if (ret)
3360 #ifdef HAVE_GAI_STRERROR
3361 error ("%s/%s %s", SDATA (host), portstring, gai_strerror(ret));
3362 #else
3363 error ("%s/%s getaddrinfo error %d", SDATA (host), portstring, ret);
3364 #endif
3365 immediate_quit = 0;
3366
3367 goto open_socket;
3368 }
3369 #endif /* HAVE_GETADDRINFO */
3370
3371 /* We end up here if getaddrinfo is not defined, or in case no hostname
3372 has been specified (e.g. for a local server process). */
3373
3374 if (EQ (service, Qt))
3375 port = 0;
3376 else if (INTEGERP (service))
3377 port = htons ((unsigned short) XINT (service));
3378 else
3379 {
3380 struct servent *svc_info;
3381 CHECK_STRING (service);
3382 svc_info = getservbyname (SDATA (service),
3383 (socktype == SOCK_DGRAM ? "udp" : "tcp"));
3384 if (svc_info == 0)
3385 error ("Unknown service: %s", SDATA (service));
3386 port = svc_info->s_port;
3387 }
3388
3389 bzero (&address_in, sizeof address_in);
3390 address_in.sin_family = family;
3391 address_in.sin_addr.s_addr = INADDR_ANY;
3392 address_in.sin_port = port;
3393
3394 #ifndef HAVE_GETADDRINFO
3395 if (!NILP (host))
3396 {
3397 struct hostent *host_info_ptr;
3398
3399 /* gethostbyname may fail with TRY_AGAIN, but we don't honour that,
3400 as it may `hang' Emacs for a very long time. */
3401 immediate_quit = 1;
3402 QUIT;
3403
3404 #ifdef HAVE_RES_INIT
3405 res_init ();
3406 #endif
3407
3408 host_info_ptr = gethostbyname (SDATA (host));
3409 immediate_quit = 0;
3410
3411 if (host_info_ptr)
3412 {
3413 bcopy (host_info_ptr->h_addr, (char *) &address_in.sin_addr,
3414 host_info_ptr->h_length);
3415 family = host_info_ptr->h_addrtype;
3416 address_in.sin_family = family;
3417 }
3418 else
3419 /* Attempt to interpret host as numeric inet address */
3420 {
3421 unsigned long numeric_addr;
3422 numeric_addr = inet_addr ((char *) SDATA (host));
3423 if (numeric_addr == -1)
3424 error ("Unknown host \"%s\"", SDATA (host));
3425
3426 bcopy ((char *)&numeric_addr, (char *) &address_in.sin_addr,
3427 sizeof (address_in.sin_addr));
3428 }
3429
3430 }
3431 #endif /* not HAVE_GETADDRINFO */
3432
3433 ai.ai_family = family;
3434 ai.ai_addr = (struct sockaddr *) &address_in;
3435 ai.ai_addrlen = sizeof address_in;
3436
3437 open_socket:
3438
3439 /* Do this in case we never enter the for-loop below. */
3440 count1 = SPECPDL_INDEX ();
3441 s = -1;
3442
3443 for (lres = res; lres; lres = lres->ai_next)
3444 {
3445 int optn, optbits;
3446
3447 retry_connect:
3448
3449 s = socket (lres->ai_family, lres->ai_socktype, lres->ai_protocol);
3450 if (s < 0)
3451 {
3452 xerrno = errno;
3453 continue;
3454 }
3455
3456 #ifdef DATAGRAM_SOCKETS
3457 if (!is_server && socktype == SOCK_DGRAM)
3458 break;
3459 #endif /* DATAGRAM_SOCKETS */
3460
3461 #ifdef NON_BLOCKING_CONNECT
3462 if (is_non_blocking_client)
3463 {
3464 #ifdef O_NONBLOCK
3465 ret = fcntl (s, F_SETFL, O_NONBLOCK);
3466 #else
3467 ret = fcntl (s, F_SETFL, O_NDELAY);
3468 #endif
3469 if (ret < 0)
3470 {
3471 xerrno = errno;
3472 emacs_close (s);
3473 s = -1;
3474 continue;
3475 }
3476 }
3477 #endif
3478
3479 /* Make us close S if quit. */
3480 record_unwind_protect (close_file_unwind, make_number (s));
3481
3482 /* Parse network options in the arg list.
3483 We simply ignore anything which isn't a known option (including other keywords).
3484 An error is signaled if setting a known option fails. */
3485 for (optn = optbits = 0; optn < nargs-1; optn += 2)
3486 optbits |= set_socket_option (s, args[optn], args[optn+1]);
3487
3488 if (is_server)
3489 {
3490 /* Configure as a server socket. */
3491
3492 /* SO_REUSEADDR = 1 is default for server sockets; must specify
3493 explicit :reuseaddr key to override this. */
3494 #ifdef HAVE_LOCAL_SOCKETS
3495 if (family != AF_LOCAL)
3496 #endif
3497 if (!(optbits & (1 << OPIX_REUSEADDR)))
3498 {
3499 int optval = 1;
3500 if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval))
3501 report_file_error ("Cannot set reuse option on server socket", Qnil);
3502 }
3503
3504 if (bind (s, lres->ai_addr, lres->ai_addrlen))
3505 report_file_error ("Cannot bind server socket", Qnil);
3506
3507 #ifdef HAVE_GETSOCKNAME
3508 if (EQ (service, Qt))
3509 {
3510 struct sockaddr_in sa1;
3511 int len1 = sizeof (sa1);
3512 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3513 {
3514 ((struct sockaddr_in *)(lres->ai_addr))->sin_port = sa1.sin_port;
3515 service = make_number (ntohs (sa1.sin_port));
3516 contact = Fplist_put (contact, QCservice, service);
3517 }
3518 }
3519 #endif
3520
3521 if (socktype == SOCK_STREAM && listen (s, backlog))
3522 report_file_error ("Cannot listen on server socket", Qnil);
3523
3524 break;
3525 }
3526
3527 immediate_quit = 1;
3528 QUIT;
3529
3530 /* This turns off all alarm-based interrupts; the
3531 bind_polling_period call above doesn't always turn all the
3532 short-interval ones off, especially if interrupt_input is
3533 set.
3534
3535 It'd be nice to be able to control the connect timeout
3536 though. Would non-blocking connect calls be portable?
3537
3538 This used to be conditioned by HAVE_GETADDRINFO. Why? */
3539
3540 turn_on_atimers (0);
3541
3542 ret = connect (s, lres->ai_addr, lres->ai_addrlen);
3543 xerrno = errno;
3544
3545 turn_on_atimers (1);
3546
3547 if (ret == 0 || xerrno == EISCONN)
3548 {
3549 /* The unwind-protect will be discarded afterwards.
3550 Likewise for immediate_quit. */
3551 break;
3552 }
3553
3554 #ifdef NON_BLOCKING_CONNECT
3555 #ifdef EINPROGRESS
3556 if (is_non_blocking_client && xerrno == EINPROGRESS)
3557 break;
3558 #else
3559 #ifdef EWOULDBLOCK
3560 if (is_non_blocking_client && xerrno == EWOULDBLOCK)
3561 break;
3562 #endif
3563 #endif
3564 #endif
3565
3566 immediate_quit = 0;
3567
3568 /* Discard the unwind protect closing S. */
3569 specpdl_ptr = specpdl + count1;
3570 emacs_close (s);
3571 s = -1;
3572
3573 if (xerrno == EINTR)
3574 goto retry_connect;
3575 }
3576
3577 if (s >= 0)
3578 {
3579 #ifdef DATAGRAM_SOCKETS
3580 if (socktype == SOCK_DGRAM)
3581 {
3582 if (datagram_address[s].sa)
3583 abort ();
3584 datagram_address[s].sa = (struct sockaddr *) xmalloc (lres->ai_addrlen);
3585 datagram_address[s].len = lres->ai_addrlen;
3586 if (is_server)
3587 {
3588 Lisp_Object remote;
3589 bzero (datagram_address[s].sa, lres->ai_addrlen);
3590 if (remote = Fplist_get (contact, QCremote), !NILP (remote))
3591 {
3592 int rfamily, rlen;
3593 rlen = get_lisp_to_sockaddr_size (remote, &rfamily);
3594 if (rfamily == lres->ai_family && rlen == lres->ai_addrlen)
3595 conv_lisp_to_sockaddr (rfamily, remote,
3596 datagram_address[s].sa, rlen);
3597 }
3598 }
3599 else
3600 bcopy (lres->ai_addr, datagram_address[s].sa, lres->ai_addrlen);
3601 }
3602 #endif
3603 contact = Fplist_put (contact, QCaddress,
3604 conv_sockaddr_to_lisp (lres->ai_addr, lres->ai_addrlen));
3605 #ifdef HAVE_GETSOCKNAME
3606 if (!is_server)
3607 {
3608 struct sockaddr_in sa1;
3609 int len1 = sizeof (sa1);
3610 if (getsockname (s, (struct sockaddr *)&sa1, &len1) == 0)
3611 contact = Fplist_put (contact, QClocal,
3612 conv_sockaddr_to_lisp (&sa1, len1));
3613 }
3614 #endif
3615 }
3616
3617 immediate_quit = 0;
3618
3619 #ifdef HAVE_GETADDRINFO
3620 if (res != &ai)
3621 {
3622 BLOCK_INPUT;
3623 freeaddrinfo (res);
3624 UNBLOCK_INPUT;
3625 }
3626 #endif
3627
3628 /* Discard the unwind protect for closing S, if any. */
3629 specpdl_ptr = specpdl + count1;
3630
3631 /* Unwind bind_polling_period and request_sigio. */
3632 unbind_to (count, Qnil);
3633
3634 if (s < 0)
3635 {
3636 /* If non-blocking got this far - and failed - assume non-blocking is
3637 not supported after all. This is probably a wrong assumption, but
3638 the normal blocking calls to open-network-stream handles this error
3639 better. */
3640 if (is_non_blocking_client)
3641 return Qnil;
3642
3643 errno = xerrno;
3644 if (is_server)
3645 report_file_error ("make server process failed", contact);
3646 else
3647 report_file_error ("make client process failed", contact);
3648 }
3649
3650 inch = s;
3651 outch = s;
3652
3653 if (!NILP (buffer))
3654 buffer = Fget_buffer_create (buffer);
3655 proc = make_process (name);
3656
3657 chan_process[inch] = proc;
3658
3659 #ifdef O_NONBLOCK
3660 fcntl (inch, F_SETFL, O_NONBLOCK);
3661 #else
3662 #ifdef O_NDELAY
3663 fcntl (inch, F_SETFL, O_NDELAY);
3664 #endif
3665 #endif
3666
3667 p = XPROCESS (proc);
3668
3669 p->childp = contact;
3670 p->plist = Fcopy_sequence (Fplist_get (contact, QCplist));
3671 p->type = Qnetwork;
3672
3673 p->buffer = buffer;
3674 p->sentinel = sentinel;
3675 p->filter = filter;
3676 p->log = Fplist_get (contact, QClog);
3677 if (tem = Fplist_get (contact, QCnoquery), !NILP (tem))
3678 p->kill_without_query = 1;
3679 if ((tem = Fplist_get (contact, QCstop), !NILP (tem)))
3680 p->command = Qt;
3681 p->pid = 0;
3682 p->infd = inch;
3683 p->outfd = outch;
3684 if (is_server && socktype == SOCK_STREAM)
3685 p->status = Qlisten;
3686
3687 /* Make the process marker point into the process buffer (if any). */
3688 if (BUFFERP (buffer))
3689 set_marker_both (p->mark, buffer,
3690 BUF_ZV (XBUFFER (buffer)),
3691 BUF_ZV_BYTE (XBUFFER (buffer)));
3692
3693 #ifdef NON_BLOCKING_CONNECT
3694 if (is_non_blocking_client)
3695 {
3696 /* We may get here if connect did succeed immediately. However,
3697 in that case, we still need to signal this like a non-blocking
3698 connection. */
3699 p->status = Qconnect;
3700 if (!FD_ISSET (inch, &connect_wait_mask))
3701 {
3702 FD_SET (inch, &connect_wait_mask);
3703 num_pending_connects++;
3704 }
3705 }
3706 else
3707 #endif
3708 /* A server may have a client filter setting of Qt, but it must
3709 still listen for incoming connects unless it is stopped. */
3710 if ((!EQ (p->filter, Qt) && !EQ (p->command, Qt))
3711 || (EQ (p->status, Qlisten) && NILP (p->command)))
3712 {
3713 FD_SET (inch, &input_wait_mask);
3714 FD_SET (inch, &non_keyboard_wait_mask);
3715 }
3716
3717 if (inch > max_process_desc)
3718 max_process_desc = inch;
3719
3720 tem = Fplist_member (contact, QCcoding);
3721 if (!NILP (tem) && (!CONSP (tem) || !CONSP (XCDR (tem))))
3722 tem = Qnil; /* No error message (too late!). */
3723
3724 {
3725 /* Setup coding systems for communicating with the network stream. */
3726 struct gcpro gcpro1;
3727 /* Qt denotes we have not yet called Ffind_operation_coding_system. */
3728 Lisp_Object coding_systems = Qt;
3729 Lisp_Object args[5], val;
3730
3731 if (!NILP (tem))
3732 {
3733 val = XCAR (XCDR (tem));
3734 if (CONSP (val))
3735 val = XCAR (val);
3736 }
3737 else if (!NILP (Vcoding_system_for_read))
3738 val = Vcoding_system_for_read;
3739 else if ((!NILP (buffer) && NILP (XBUFFER (buffer)->enable_multibyte_characters))
3740 || (NILP (buffer) && NILP (buffer_defaults.enable_multibyte_characters)))
3741 /* We dare not decode end-of-line format by setting VAL to
3742 Qraw_text, because the existing Emacs Lisp libraries
3743 assume that they receive bare code including a sequene of
3744 CR LF. */
3745 val = Qnil;
3746 else
3747 {
3748 if (NILP (host) || NILP (service))
3749 coding_systems = Qnil;
3750 else
3751 {
3752 args[0] = Qopen_network_stream, args[1] = name,
3753 args[2] = buffer, args[3] = host, args[4] = service;
3754 GCPRO1 (proc);
3755 coding_systems = Ffind_operation_coding_system (5, args);
3756 UNGCPRO;
3757 }
3758 if (CONSP (coding_systems))
3759 val = XCAR (coding_systems);
3760 else if (CONSP (Vdefault_process_coding_system))
3761 val = XCAR (Vdefault_process_coding_system);
3762 else
3763 val = Qnil;
3764 }
3765 p->decode_coding_system = val;
3766
3767 if (!NILP (tem))
3768 {
3769 val = XCAR (XCDR (tem));
3770 if (CONSP (val))
3771 val = XCDR (val);
3772 }
3773 else if (!NILP (Vcoding_system_for_write))
3774 val = Vcoding_system_for_write;
3775 else if (NILP (current_buffer->enable_multibyte_characters))
3776 val = Qnil;
3777 else
3778 {
3779 if (EQ (coding_systems, Qt))
3780 {
3781 if (NILP (host) || NILP (service))
3782 coding_systems = Qnil;
3783 else
3784 {
3785 args[0] = Qopen_network_stream, args[1] = name,
3786 args[2] = buffer, args[3] = host, args[4] = service;
3787 GCPRO1 (proc);
3788 coding_systems = Ffind_operation_coding_system (5, args);
3789 UNGCPRO;
3790 }
3791 }
3792 if (CONSP (coding_systems))
3793 val = XCDR (coding_systems);
3794 else if (CONSP (Vdefault_process_coding_system))
3795 val = XCDR (Vdefault_process_coding_system);
3796 else
3797 val = Qnil;
3798 }
3799 p->encode_coding_system = val;
3800 }
3801 setup_process_coding_systems (proc);
3802
3803 p->decoding_buf = make_uninit_string (0);
3804 p->decoding_carryover = 0;
3805 p->encoding_buf = make_uninit_string (0);
3806
3807 p->inherit_coding_system_flag
3808 = !(!NILP (tem) || NILP (buffer) || !inherit_process_coding_system);
3809
3810 UNGCPRO;
3811 return proc;
3812 }
3813 #endif /* HAVE_SOCKETS */
3814
3815 \f
3816 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
3817
3818 #ifdef SIOCGIFCONF
3819 DEFUN ("network-interface-list", Fnetwork_interface_list, Snetwork_interface_list, 0, 0, 0,
3820 doc: /* Return an alist of all network interfaces and their network address.
3821 Each element is a cons, the car of which is a string containing the
3822 interface name, and the cdr is the network address in internal
3823 format; see the description of ADDRESS in `make-network-process'. */)
3824 ()
3825 {
3826 struct ifconf ifconf;
3827 struct ifreq *ifreqs = NULL;
3828 int ifaces = 0;
3829 int buf_size, s;
3830 Lisp_Object res;
3831
3832 s = socket (AF_INET, SOCK_STREAM, 0);
3833 if (s < 0)
3834 return Qnil;
3835
3836 again:
3837 ifaces += 25;
3838 buf_size = ifaces * sizeof(ifreqs[0]);
3839 ifreqs = (struct ifreq *)xrealloc(ifreqs, buf_size);
3840 if (!ifreqs)
3841 {
3842 close (s);
3843 return Qnil;
3844 }
3845
3846 ifconf.ifc_len = buf_size;
3847 ifconf.ifc_req = ifreqs;
3848 if (ioctl (s, SIOCGIFCONF, &ifconf))
3849 {
3850 close (s);
3851 return Qnil;
3852 }
3853
3854 if (ifconf.ifc_len == buf_size)
3855 goto again;
3856
3857 close (s);
3858 ifaces = ifconf.ifc_len / sizeof (ifreqs[0]);
3859
3860 res = Qnil;
3861 while (--ifaces >= 0)
3862 {
3863 struct ifreq *ifq = &ifreqs[ifaces];
3864 char namebuf[sizeof (ifq->ifr_name) + 1];
3865 if (ifq->ifr_addr.sa_family != AF_INET)
3866 continue;
3867 bcopy (ifq->ifr_name, namebuf, sizeof (ifq->ifr_name));
3868 namebuf[sizeof (ifq->ifr_name)] = 0;
3869 res = Fcons (Fcons (build_string (namebuf),
3870 conv_sockaddr_to_lisp (&ifq->ifr_addr,
3871 sizeof (struct sockaddr))),
3872 res);
3873 }
3874
3875 return res;
3876 }
3877 #endif /* SIOCGIFCONF */
3878
3879 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
3880
3881 struct ifflag_def {
3882 int flag_bit;
3883 char *flag_sym;
3884 };
3885
3886 static struct ifflag_def ifflag_table[] = {
3887 #ifdef IFF_UP
3888 { IFF_UP, "up" },
3889 #endif
3890 #ifdef IFF_BROADCAST
3891 { IFF_BROADCAST, "broadcast" },
3892 #endif
3893 #ifdef IFF_DEBUG
3894 { IFF_DEBUG, "debug" },
3895 #endif
3896 #ifdef IFF_LOOPBACK
3897 { IFF_LOOPBACK, "loopback" },
3898 #endif
3899 #ifdef IFF_POINTOPOINT
3900 { IFF_POINTOPOINT, "pointopoint" },
3901 #endif
3902 #ifdef IFF_RUNNING
3903 { IFF_RUNNING, "running" },
3904 #endif
3905 #ifdef IFF_NOARP
3906 { IFF_NOARP, "noarp" },
3907 #endif
3908 #ifdef IFF_PROMISC
3909 { IFF_PROMISC, "promisc" },
3910 #endif
3911 #ifdef IFF_NOTRAILERS
3912 { IFF_NOTRAILERS, "notrailers" },
3913 #endif
3914 #ifdef IFF_ALLMULTI
3915 { IFF_ALLMULTI, "allmulti" },
3916 #endif
3917 #ifdef IFF_MASTER
3918 { IFF_MASTER, "master" },
3919 #endif
3920 #ifdef IFF_SLAVE
3921 { IFF_SLAVE, "slave" },
3922 #endif
3923 #ifdef IFF_MULTICAST
3924 { IFF_MULTICAST, "multicast" },
3925 #endif
3926 #ifdef IFF_PORTSEL
3927 { IFF_PORTSEL, "portsel" },
3928 #endif
3929 #ifdef IFF_AUTOMEDIA
3930 { IFF_AUTOMEDIA, "automedia" },
3931 #endif
3932 #ifdef IFF_DYNAMIC
3933 { IFF_DYNAMIC, "dynamic" },
3934 #endif
3935 #ifdef IFF_OACTIVE
3936 { IFF_OACTIVE, "oactive" }, /* OpenBSD: transmission in progress */
3937 #endif
3938 #ifdef IFF_SIMPLEX
3939 { IFF_SIMPLEX, "simplex" }, /* OpenBSD: can't hear own transmissions */
3940 #endif
3941 #ifdef IFF_LINK0
3942 { IFF_LINK0, "link0" }, /* OpenBSD: per link layer defined bit */
3943 #endif
3944 #ifdef IFF_LINK1
3945 { IFF_LINK1, "link1" }, /* OpenBSD: per link layer defined bit */
3946 #endif
3947 #ifdef IFF_LINK2
3948 { IFF_LINK2, "link2" }, /* OpenBSD: per link layer defined bit */
3949 #endif
3950 { 0, 0 }
3951 };
3952
3953 DEFUN ("network-interface-info", Fnetwork_interface_info, Snetwork_interface_info, 1, 1, 0,
3954 doc: /* Return information about network interface named IFNAME.
3955 The return value is a list (ADDR BCAST NETMASK HWADDR FLAGS),
3956 where ADDR is the layer 3 address, BCAST is the layer 3 broadcast address,
3957 NETMASK is the layer 3 network mask, HWADDR is the layer 2 addres, and
3958 FLAGS is the current flags of the interface. */)
3959 (ifname)
3960 Lisp_Object ifname;
3961 {
3962 struct ifreq rq;
3963 Lisp_Object res = Qnil;
3964 Lisp_Object elt;
3965 int s;
3966 int any = 0;
3967
3968 CHECK_STRING (ifname);
3969
3970 bzero (rq.ifr_name, sizeof rq.ifr_name);
3971 strncpy (rq.ifr_name, SDATA (ifname), sizeof (rq.ifr_name));
3972
3973 s = socket (AF_INET, SOCK_STREAM, 0);
3974 if (s < 0)
3975 return Qnil;
3976
3977 elt = Qnil;
3978 #if defined(SIOCGIFFLAGS) && defined(HAVE_STRUCT_IFREQ_IFR_FLAGS)
3979 if (ioctl (s, SIOCGIFFLAGS, &rq) == 0)
3980 {
3981 int flags = rq.ifr_flags;
3982 struct ifflag_def *fp;
3983 int fnum;
3984
3985 any++;
3986 for (fp = ifflag_table; flags != 0 && fp->flag_sym; fp++)
3987 {
3988 if (flags & fp->flag_bit)
3989 {
3990 elt = Fcons (intern (fp->flag_sym), elt);
3991 flags -= fp->flag_bit;
3992 }
3993 }
3994 for (fnum = 0; flags && fnum < 32; fnum++)
3995 {
3996 if (flags & (1 << fnum))
3997 {
3998 elt = Fcons (make_number (fnum), elt);
3999 }
4000 }
4001 }
4002 #endif
4003 res = Fcons (elt, res);
4004
4005 elt = Qnil;
4006 #if defined(SIOCGIFHWADDR) && defined(HAVE_STRUCT_IFREQ_IFR_HWADDR)
4007 if (ioctl (s, SIOCGIFHWADDR, &rq) == 0)
4008 {
4009 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
4010 register struct Lisp_Vector *p = XVECTOR (hwaddr);
4011 int n;
4012
4013 any++;
4014 for (n = 0; n < 6; n++)
4015 p->contents[n] = make_number (((unsigned char *)&rq.ifr_hwaddr.sa_data[0])[n]);
4016 elt = Fcons (make_number (rq.ifr_hwaddr.sa_family), hwaddr);
4017 }
4018 #endif
4019 res = Fcons (elt, res);
4020
4021 elt = Qnil;
4022 #if defined(SIOCGIFNETMASK) && (defined(HAVE_STRUCT_IFREQ_IFR_NETMASK) || defined(HAVE_STRUCT_IFREQ_IFR_ADDR))
4023 if (ioctl (s, SIOCGIFNETMASK, &rq) == 0)
4024 {
4025 any++;
4026 #ifdef HAVE_STRUCT_IFREQ_IFR_NETMASK
4027 elt = conv_sockaddr_to_lisp (&rq.ifr_netmask, sizeof (rq.ifr_netmask));
4028 #else
4029 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4030 #endif
4031 }
4032 #endif
4033 res = Fcons (elt, res);
4034
4035 elt = Qnil;
4036 #if defined(SIOCGIFBRDADDR) && defined(HAVE_STRUCT_IFREQ_IFR_BROADADDR)
4037 if (ioctl (s, SIOCGIFBRDADDR, &rq) == 0)
4038 {
4039 any++;
4040 elt = conv_sockaddr_to_lisp (&rq.ifr_broadaddr, sizeof (rq.ifr_broadaddr));
4041 }
4042 #endif
4043 res = Fcons (elt, res);
4044
4045 elt = Qnil;
4046 #if defined(SIOCGIFADDR) && defined(HAVE_STRUCT_IFREQ_IFR_ADDR)
4047 if (ioctl (s, SIOCGIFADDR, &rq) == 0)
4048 {
4049 any++;
4050 elt = conv_sockaddr_to_lisp (&rq.ifr_addr, sizeof (rq.ifr_addr));
4051 }
4052 #endif
4053 res = Fcons (elt, res);
4054
4055 close (s);
4056
4057 return any ? res : Qnil;
4058 }
4059 #endif
4060 #endif /* HAVE_SOCKETS */
4061
4062 /* Turn off input and output for process PROC. */
4063
4064 void
4065 deactivate_process (proc)
4066 Lisp_Object proc;
4067 {
4068 register int inchannel, outchannel;
4069 register struct Lisp_Process *p = XPROCESS (proc);
4070
4071 inchannel = p->infd;
4072 outchannel = p->outfd;
4073
4074 #ifdef ADAPTIVE_READ_BUFFERING
4075 if (p->read_output_delay > 0)
4076 {
4077 if (--process_output_delay_count < 0)
4078 process_output_delay_count = 0;
4079 p->read_output_delay = 0;
4080 p->read_output_skip = 0;
4081 }
4082 #endif
4083
4084 if (inchannel >= 0)
4085 {
4086 /* Beware SIGCHLD hereabouts. */
4087 flush_pending_output (inchannel);
4088 emacs_close (inchannel);
4089 if (outchannel >= 0 && outchannel != inchannel)
4090 emacs_close (outchannel);
4091
4092 p->infd = -1;
4093 p->outfd = -1;
4094 #ifdef DATAGRAM_SOCKETS
4095 if (DATAGRAM_CHAN_P (inchannel))
4096 {
4097 xfree (datagram_address[inchannel].sa);
4098 datagram_address[inchannel].sa = 0;
4099 datagram_address[inchannel].len = 0;
4100 }
4101 #endif
4102 chan_process[inchannel] = Qnil;
4103 FD_CLR (inchannel, &input_wait_mask);
4104 FD_CLR (inchannel, &non_keyboard_wait_mask);
4105 #ifdef NON_BLOCKING_CONNECT
4106 if (FD_ISSET (inchannel, &connect_wait_mask))
4107 {
4108 FD_CLR (inchannel, &connect_wait_mask);
4109 if (--num_pending_connects < 0)
4110 abort ();
4111 }
4112 #endif
4113 if (inchannel == max_process_desc)
4114 {
4115 int i;
4116 /* We just closed the highest-numbered process input descriptor,
4117 so recompute the highest-numbered one now. */
4118 max_process_desc = 0;
4119 for (i = 0; i < MAXDESC; i++)
4120 if (!NILP (chan_process[i]))
4121 max_process_desc = i;
4122 }
4123 }
4124 }
4125
4126 /* Close all descriptors currently in use for communication
4127 with subprocess. This is used in a newly-forked subprocess
4128 to get rid of irrelevant descriptors. */
4129
4130 void
4131 close_process_descs ()
4132 {
4133 #ifndef WINDOWSNT
4134 int i;
4135 for (i = 0; i < MAXDESC; i++)
4136 {
4137 Lisp_Object process;
4138 process = chan_process[i];
4139 if (!NILP (process))
4140 {
4141 int in = XPROCESS (process)->infd;
4142 int out = XPROCESS (process)->outfd;
4143 if (in >= 0)
4144 emacs_close (in);
4145 if (out >= 0 && in != out)
4146 emacs_close (out);
4147 }
4148 }
4149 #endif
4150 }
4151 \f
4152 DEFUN ("accept-process-output", Faccept_process_output, Saccept_process_output,
4153 0, 4, 0,
4154 doc: /* Allow any pending output from subprocesses to be read by Emacs.
4155 It is read into the process' buffers or given to their filter functions.
4156 Non-nil arg PROCESS means do not return until some output has been received
4157 from PROCESS.
4158
4159 Non-nil second arg SECONDS and third arg MILLISEC are number of seconds
4160 and milliseconds to wait; return after that much time whether or not
4161 there is any subprocess output. If SECONDS is a floating point number,
4162 it specifies a fractional number of seconds to wait.
4163 The MILLISEC argument is obsolete and should be avoided.
4164
4165 If optional fourth arg JUST-THIS-ONE is non-nil, only accept output
4166 from PROCESS, suspending reading output from other processes.
4167 If JUST-THIS-ONE is an integer, don't run any timers either.
4168 Return non-nil if we received any output before the timeout expired. */)
4169 (process, seconds, millisec, just_this_one)
4170 register Lisp_Object process, seconds, millisec, just_this_one;
4171 {
4172 int secs, usecs = 0;
4173
4174 if (! NILP (process))
4175 CHECK_PROCESS (process);
4176 else
4177 just_this_one = Qnil;
4178
4179 if (!NILP (millisec))
4180 { /* Obsolete calling convention using integers rather than floats. */
4181 CHECK_NUMBER (millisec);
4182 if (NILP (seconds))
4183 seconds = make_float (XINT (millisec) / 1000.0);
4184 else
4185 {
4186 CHECK_NUMBER (seconds);
4187 seconds = make_float (XINT (millisec) / 1000.0 + XINT (seconds));
4188 }
4189 }
4190
4191 if (!NILP (seconds))
4192 {
4193 if (INTEGERP (seconds))
4194 secs = XINT (seconds);
4195 else if (FLOATP (seconds))
4196 {
4197 double timeout = XFLOAT_DATA (seconds);
4198 secs = (int) timeout;
4199 usecs = (int) ((timeout - (double) secs) * 1000000);
4200 }
4201 else
4202 wrong_type_argument (Qnumberp, seconds);
4203
4204 if (secs < 0 || (secs == 0 && usecs == 0))
4205 secs = -1, usecs = 0;
4206 }
4207 else
4208 secs = NILP (process) ? -1 : 0;
4209
4210 return
4211 (wait_reading_process_output (secs, usecs, 0, 0,
4212 Qnil,
4213 !NILP (process) ? XPROCESS (process) : NULL,
4214 NILP (just_this_one) ? 0 :
4215 !INTEGERP (just_this_one) ? 1 : -1)
4216 ? Qt : Qnil);
4217 }
4218
4219 /* Accept a connection for server process SERVER on CHANNEL. */
4220
4221 static int connect_counter = 0;
4222
4223 static void
4224 server_accept_connection (server, channel)
4225 Lisp_Object server;
4226 int channel;
4227 {
4228 Lisp_Object proc, caller, name, buffer;
4229 Lisp_Object contact, host, service;
4230 struct Lisp_Process *ps= XPROCESS (server);
4231 struct Lisp_Process *p;
4232 int s;
4233 union u_sockaddr {
4234 struct sockaddr sa;
4235 struct sockaddr_in in;
4236 #ifdef AF_INET6
4237 struct sockaddr_in6 in6;
4238 #endif
4239 #ifdef HAVE_LOCAL_SOCKETS
4240 struct sockaddr_un un;
4241 #endif
4242 } saddr;
4243 int len = sizeof saddr;
4244
4245 s = accept (channel, &saddr.sa, &len);
4246
4247 if (s < 0)
4248 {
4249 int code = errno;
4250
4251 if (code == EAGAIN)
4252 return;
4253 #ifdef EWOULDBLOCK
4254 if (code == EWOULDBLOCK)
4255 return;
4256 #endif
4257
4258 if (!NILP (ps->log))
4259 call3 (ps->log, server, Qnil,
4260 concat3 (build_string ("accept failed with code"),
4261 Fnumber_to_string (make_number (code)),
4262 build_string ("\n")));
4263 return;
4264 }
4265
4266 connect_counter++;
4267
4268 /* Setup a new process to handle the connection. */
4269
4270 /* Generate a unique identification of the caller, and build contact
4271 information for this process. */
4272 host = Qt;
4273 service = Qnil;
4274 switch (saddr.sa.sa_family)
4275 {
4276 case AF_INET:
4277 {
4278 Lisp_Object args[5];
4279 unsigned char *ip = (unsigned char *)&saddr.in.sin_addr.s_addr;
4280 args[0] = build_string ("%d.%d.%d.%d");
4281 args[1] = make_number (*ip++);
4282 args[2] = make_number (*ip++);
4283 args[3] = make_number (*ip++);
4284 args[4] = make_number (*ip++);
4285 host = Fformat (5, args);
4286 service = make_number (ntohs (saddr.in.sin_port));
4287
4288 args[0] = build_string (" <%s:%d>");
4289 args[1] = host;
4290 args[2] = service;
4291 caller = Fformat (3, args);
4292 }
4293 break;
4294
4295 #ifdef AF_INET6
4296 case AF_INET6:
4297 {
4298 Lisp_Object args[9];
4299 uint16_t *ip6 = (uint16_t *)&saddr.in6.sin6_addr;
4300 int i;
4301 args[0] = build_string ("%x:%x:%x:%x:%x:%x:%x:%x");
4302 for (i = 0; i < 8; i++)
4303 args[i+1] = make_number (ntohs(ip6[i]));
4304 host = Fformat (9, args);
4305 service = make_number (ntohs (saddr.in.sin_port));
4306
4307 args[0] = build_string (" <[%s]:%d>");
4308 args[1] = host;
4309 args[2] = service;
4310 caller = Fformat (3, args);
4311 }
4312 break;
4313 #endif
4314
4315 #ifdef HAVE_LOCAL_SOCKETS
4316 case AF_LOCAL:
4317 #endif
4318 default:
4319 caller = Fnumber_to_string (make_number (connect_counter));
4320 caller = concat3 (build_string (" <"), caller, build_string (">"));
4321 break;
4322 }
4323
4324 /* Create a new buffer name for this process if it doesn't have a
4325 filter. The new buffer name is based on the buffer name or
4326 process name of the server process concatenated with the caller
4327 identification. */
4328
4329 if (!NILP (ps->filter) && !EQ (ps->filter, Qt))
4330 buffer = Qnil;
4331 else
4332 {
4333 buffer = ps->buffer;
4334 if (!NILP (buffer))
4335 buffer = Fbuffer_name (buffer);
4336 else
4337 buffer = ps->name;
4338 if (!NILP (buffer))
4339 {
4340 buffer = concat2 (buffer, caller);
4341 buffer = Fget_buffer_create (buffer);
4342 }
4343 }
4344
4345 /* Generate a unique name for the new server process. Combine the
4346 server process name with the caller identification. */
4347
4348 name = concat2 (ps->name, caller);
4349 proc = make_process (name);
4350
4351 chan_process[s] = proc;
4352
4353 #ifdef O_NONBLOCK
4354 fcntl (s, F_SETFL, O_NONBLOCK);
4355 #else
4356 #ifdef O_NDELAY
4357 fcntl (s, F_SETFL, O_NDELAY);
4358 #endif
4359 #endif
4360
4361 p = XPROCESS (proc);
4362
4363 /* Build new contact information for this setup. */
4364 contact = Fcopy_sequence (ps->childp);
4365 contact = Fplist_put (contact, QCserver, Qnil);
4366 contact = Fplist_put (contact, QChost, host);
4367 if (!NILP (service))
4368 contact = Fplist_put (contact, QCservice, service);
4369 contact = Fplist_put (contact, QCremote,
4370 conv_sockaddr_to_lisp (&saddr.sa, len));
4371 #ifdef HAVE_GETSOCKNAME
4372 len = sizeof saddr;
4373 if (getsockname (s, &saddr.sa, &len) == 0)
4374 contact = Fplist_put (contact, QClocal,
4375 conv_sockaddr_to_lisp (&saddr.sa, len));
4376 #endif
4377
4378 p->childp = contact;
4379 p->plist = Fcopy_sequence (ps->plist);
4380 p->type = Qnetwork;
4381
4382 p->buffer = buffer;
4383 p->sentinel = ps->sentinel;
4384 p->filter = ps->filter;
4385 p->command = Qnil;
4386 p->pid = 0;
4387 p->infd = s;
4388 p->outfd = s;
4389 p->status = Qrun;
4390
4391 /* Client processes for accepted connections are not stopped initially. */
4392 if (!EQ (p->filter, Qt))
4393 {
4394 FD_SET (s, &input_wait_mask);
4395 FD_SET (s, &non_keyboard_wait_mask);
4396 }
4397
4398 if (s > max_process_desc)
4399 max_process_desc = s;
4400
4401 /* Setup coding system for new process based on server process.
4402 This seems to be the proper thing to do, as the coding system
4403 of the new process should reflect the settings at the time the
4404 server socket was opened; not the current settings. */
4405
4406 p->decode_coding_system = ps->decode_coding_system;
4407 p->encode_coding_system = ps->encode_coding_system;
4408 setup_process_coding_systems (proc);
4409
4410 p->decoding_buf = make_uninit_string (0);
4411 p->decoding_carryover = 0;
4412 p->encoding_buf = make_uninit_string (0);
4413
4414 p->inherit_coding_system_flag
4415 = (NILP (buffer) ? 0 : ps->inherit_coding_system_flag);
4416
4417 if (!NILP (ps->log))
4418 call3 (ps->log, server, proc,
4419 concat3 (build_string ("accept from "),
4420 (STRINGP (host) ? host : build_string ("-")),
4421 build_string ("\n")));
4422
4423 if (!NILP (p->sentinel))
4424 exec_sentinel (proc,
4425 concat3 (build_string ("open from "),
4426 (STRINGP (host) ? host : build_string ("-")),
4427 build_string ("\n")));
4428 }
4429
4430 /* This variable is different from waiting_for_input in keyboard.c.
4431 It is used to communicate to a lisp process-filter/sentinel (via the
4432 function Fwaiting_for_user_input_p below) whether Emacs was waiting
4433 for user-input when that process-filter was called.
4434 waiting_for_input cannot be used as that is by definition 0 when
4435 lisp code is being evalled.
4436 This is also used in record_asynch_buffer_change.
4437 For that purpose, this must be 0
4438 when not inside wait_reading_process_output. */
4439 static int waiting_for_user_input_p;
4440
4441 static Lisp_Object
4442 wait_reading_process_output_unwind (data)
4443 Lisp_Object data;
4444 {
4445 waiting_for_user_input_p = XINT (data);
4446 return Qnil;
4447 }
4448
4449 /* This is here so breakpoints can be put on it. */
4450 static void
4451 wait_reading_process_output_1 ()
4452 {
4453 }
4454
4455 /* Use a wrapper around select to work around a bug in gdb 5.3.
4456 Normally, the wrapper is optimzed away by inlining.
4457
4458 If emacs is stopped inside select, the gdb backtrace doesn't
4459 show the function which called select, so it is practically
4460 impossible to step through wait_reading_process_output. */
4461
4462 #ifndef select
4463 static INLINE int
4464 select_wrapper (n, rfd, wfd, xfd, tmo)
4465 int n;
4466 SELECT_TYPE *rfd, *wfd, *xfd;
4467 EMACS_TIME *tmo;
4468 {
4469 return select (n, rfd, wfd, xfd, tmo);
4470 }
4471 #define select select_wrapper
4472 #endif
4473
4474 /* Read and dispose of subprocess output while waiting for timeout to
4475 elapse and/or keyboard input to be available.
4476
4477 TIME_LIMIT is:
4478 timeout in seconds, or
4479 zero for no limit, or
4480 -1 means gobble data immediately available but don't wait for any.
4481
4482 MICROSECS is:
4483 an additional duration to wait, measured in microseconds.
4484 If this is nonzero and time_limit is 0, then the timeout
4485 consists of MICROSECS only.
4486
4487 READ_KBD is a lisp value:
4488 0 to ignore keyboard input, or
4489 1 to return when input is available, or
4490 -1 meaning caller will actually read the input, so don't throw to
4491 the quit handler, or
4492
4493 DO_DISPLAY != 0 means redisplay should be done to show subprocess
4494 output that arrives.
4495
4496 If WAIT_FOR_CELL is a cons cell, wait until its car is non-nil
4497 (and gobble terminal input into the buffer if any arrives).
4498
4499 If WAIT_PROC is specified, wait until something arrives from that
4500 process. The return value is true if we read some input from
4501 that process.
4502
4503 If JUST_WAIT_PROC is non-nil, handle only output from WAIT_PROC
4504 (suspending output from other processes). A negative value
4505 means don't run any timers either.
4506
4507 If WAIT_PROC is specified, then the function returns true if we
4508 received input from that process before the timeout elapsed.
4509 Otherwise, return true if we received input from any process. */
4510
4511 int
4512 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
4513 wait_for_cell, wait_proc, just_wait_proc)
4514 int time_limit, microsecs, read_kbd, do_display;
4515 Lisp_Object wait_for_cell;
4516 struct Lisp_Process *wait_proc;
4517 int just_wait_proc;
4518 {
4519 register int channel, nfds;
4520 SELECT_TYPE Available;
4521 #ifdef NON_BLOCKING_CONNECT
4522 SELECT_TYPE Connecting;
4523 int check_connect;
4524 #endif
4525 int check_delay, no_avail;
4526 int xerrno;
4527 Lisp_Object proc;
4528 EMACS_TIME timeout, end_time;
4529 int wait_channel = -1;
4530 int got_some_input = 0;
4531 int count = SPECPDL_INDEX ();
4532
4533 FD_ZERO (&Available);
4534 #ifdef NON_BLOCKING_CONNECT
4535 FD_ZERO (&Connecting);
4536 #endif
4537
4538 /* If wait_proc is a process to watch, set wait_channel accordingly. */
4539 if (wait_proc != NULL)
4540 wait_channel = wait_proc->infd;
4541
4542 record_unwind_protect (wait_reading_process_output_unwind,
4543 make_number (waiting_for_user_input_p));
4544 waiting_for_user_input_p = read_kbd;
4545
4546 /* Since we may need to wait several times,
4547 compute the absolute time to return at. */
4548 if (time_limit || microsecs)
4549 {
4550 EMACS_GET_TIME (end_time);
4551 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
4552 EMACS_ADD_TIME (end_time, end_time, timeout);
4553 }
4554
4555 while (1)
4556 {
4557 int timeout_reduced_for_timers = 0;
4558
4559 /* If calling from keyboard input, do not quit
4560 since we want to return C-g as an input character.
4561 Otherwise, do pending quit if requested. */
4562 if (read_kbd >= 0)
4563 QUIT;
4564 #ifdef SYNC_INPUT
4565 else
4566 process_pending_signals ();
4567 #endif
4568
4569 /* Exit now if the cell we're waiting for became non-nil. */
4570 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4571 break;
4572
4573 /* Compute time from now till when time limit is up */
4574 /* Exit if already run out */
4575 if (time_limit == -1)
4576 {
4577 /* -1 specified for timeout means
4578 gobble output available now
4579 but don't wait at all. */
4580
4581 EMACS_SET_SECS_USECS (timeout, 0, 0);
4582 }
4583 else if (time_limit || microsecs)
4584 {
4585 EMACS_GET_TIME (timeout);
4586 EMACS_SUB_TIME (timeout, end_time, timeout);
4587 if (EMACS_TIME_NEG_P (timeout))
4588 break;
4589 }
4590 else
4591 {
4592 EMACS_SET_SECS_USECS (timeout, 100000, 0);
4593 }
4594
4595 /* Normally we run timers here.
4596 But not if wait_for_cell; in those cases,
4597 the wait is supposed to be short,
4598 and those callers cannot handle running arbitrary Lisp code here. */
4599 if (NILP (wait_for_cell)
4600 && just_wait_proc >= 0)
4601 {
4602 EMACS_TIME timer_delay;
4603
4604 do
4605 {
4606 int old_timers_run = timers_run;
4607 struct buffer *old_buffer = current_buffer;
4608 Lisp_Object old_window = selected_window;
4609
4610 timer_delay = timer_check (1);
4611
4612 /* If a timer has run, this might have changed buffers
4613 an alike. Make read_key_sequence aware of that. */
4614 if (timers_run != old_timers_run
4615 && (old_buffer != current_buffer
4616 || !EQ (old_window, selected_window))
4617 && waiting_for_user_input_p == -1)
4618 record_asynch_buffer_change ();
4619
4620 if (timers_run != old_timers_run && do_display)
4621 /* We must retry, since a timer may have requeued itself
4622 and that could alter the time_delay. */
4623 redisplay_preserve_echo_area (9);
4624 else
4625 break;
4626 }
4627 while (!detect_input_pending ());
4628
4629 /* If there is unread keyboard input, also return. */
4630 if (read_kbd != 0
4631 && requeued_events_pending_p ())
4632 break;
4633
4634 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
4635 {
4636 EMACS_TIME difference;
4637 EMACS_SUB_TIME (difference, timer_delay, timeout);
4638 if (EMACS_TIME_NEG_P (difference))
4639 {
4640 timeout = timer_delay;
4641 timeout_reduced_for_timers = 1;
4642 }
4643 }
4644 /* If time_limit is -1, we are not going to wait at all. */
4645 else if (time_limit != -1)
4646 {
4647 /* This is so a breakpoint can be put here. */
4648 wait_reading_process_output_1 ();
4649 }
4650 }
4651
4652 /* Cause C-g and alarm signals to take immediate action,
4653 and cause input available signals to zero out timeout.
4654
4655 It is important that we do this before checking for process
4656 activity. If we get a SIGCHLD after the explicit checks for
4657 process activity, timeout is the only way we will know. */
4658 if (read_kbd < 0)
4659 set_waiting_for_input (&timeout);
4660
4661 /* If status of something has changed, and no input is
4662 available, notify the user of the change right away. After
4663 this explicit check, we'll let the SIGCHLD handler zap
4664 timeout to get our attention. When Emacs is run
4665 interactively, only do this with a nonzero DO_DISPLAY
4666 argument, because status_notify triggers redisplay. */
4667 if (update_tick != process_tick
4668 && (do_display || noninteractive))
4669 {
4670 SELECT_TYPE Atemp;
4671 #ifdef NON_BLOCKING_CONNECT
4672 SELECT_TYPE Ctemp;
4673 #endif
4674
4675 Atemp = input_wait_mask;
4676 IF_NON_BLOCKING_CONNECT (Ctemp = connect_wait_mask);
4677
4678 EMACS_SET_SECS_USECS (timeout, 0, 0);
4679 if ((select (max (max (max_process_desc, max_keyboard_desc),
4680 max_gpm_desc) + 1,
4681 &Atemp,
4682 #ifdef NON_BLOCKING_CONNECT
4683 (num_pending_connects > 0 ? &Ctemp : (SELECT_TYPE *)0),
4684 #else
4685 (SELECT_TYPE *)0,
4686 #endif
4687 (SELECT_TYPE *)0, &timeout)
4688 <= 0))
4689 {
4690 /* It's okay for us to do this and then continue with
4691 the loop, since timeout has already been zeroed out. */
4692 clear_waiting_for_input ();
4693 status_notify (NULL);
4694 }
4695 }
4696
4697 /* Don't wait for output from a non-running process. Just
4698 read whatever data has already been received. */
4699 if (wait_proc && wait_proc->raw_status_new)
4700 update_status (wait_proc);
4701 if (wait_proc
4702 && ! EQ (wait_proc->status, Qrun)
4703 && ! EQ (wait_proc->status, Qconnect))
4704 {
4705 int nread, total_nread = 0;
4706
4707 clear_waiting_for_input ();
4708 XSETPROCESS (proc, wait_proc);
4709
4710 /* Read data from the process, until we exhaust it. */
4711 while (wait_proc->infd >= 0)
4712 {
4713 nread = read_process_output (proc, wait_proc->infd);
4714
4715 if (nread == 0)
4716 break;
4717
4718 if (0 < nread)
4719 {
4720 total_nread += nread;
4721 got_some_input = 1;
4722 }
4723 #ifdef EIO
4724 else if (nread == -1 && EIO == errno)
4725 break;
4726 #endif
4727 #ifdef EAGAIN
4728 else if (nread == -1 && EAGAIN == errno)
4729 break;
4730 #endif
4731 #ifdef EWOULDBLOCK
4732 else if (nread == -1 && EWOULDBLOCK == errno)
4733 break;
4734 #endif
4735 }
4736 if (total_nread > 0 && do_display)
4737 redisplay_preserve_echo_area (10);
4738
4739 break;
4740 }
4741
4742 /* Wait till there is something to do */
4743
4744 if (wait_proc && just_wait_proc)
4745 {
4746 if (wait_proc->infd < 0) /* Terminated */
4747 break;
4748 FD_SET (wait_proc->infd, &Available);
4749 check_delay = 0;
4750 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4751 }
4752 else if (!NILP (wait_for_cell))
4753 {
4754 Available = non_process_wait_mask;
4755 check_delay = 0;
4756 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4757 }
4758 else
4759 {
4760 if (! read_kbd)
4761 Available = non_keyboard_wait_mask;
4762 else
4763 Available = input_wait_mask;
4764 IF_NON_BLOCKING_CONNECT (check_connect = (num_pending_connects > 0));
4765 check_delay = wait_channel >= 0 ? 0 : process_output_delay_count;
4766 }
4767
4768 /* If frame size has changed or the window is newly mapped,
4769 redisplay now, before we start to wait. There is a race
4770 condition here; if a SIGIO arrives between now and the select
4771 and indicates that a frame is trashed, the select may block
4772 displaying a trashed screen. */
4773 if (frame_garbaged && do_display)
4774 {
4775 clear_waiting_for_input ();
4776 redisplay_preserve_echo_area (11);
4777 if (read_kbd < 0)
4778 set_waiting_for_input (&timeout);
4779 }
4780
4781 no_avail = 0;
4782 if (read_kbd && detect_input_pending ())
4783 {
4784 nfds = 0;
4785 no_avail = 1;
4786 }
4787 else
4788 {
4789 #ifdef NON_BLOCKING_CONNECT
4790 if (check_connect)
4791 Connecting = connect_wait_mask;
4792 #endif
4793
4794 #ifdef ADAPTIVE_READ_BUFFERING
4795 /* Set the timeout for adaptive read buffering if any
4796 process has non-zero read_output_skip and non-zero
4797 read_output_delay, and we are not reading output for a
4798 specific wait_channel. It is not executed if
4799 Vprocess_adaptive_read_buffering is nil. */
4800 if (process_output_skip && check_delay > 0)
4801 {
4802 int usecs = EMACS_USECS (timeout);
4803 if (EMACS_SECS (timeout) > 0 || usecs > READ_OUTPUT_DELAY_MAX)
4804 usecs = READ_OUTPUT_DELAY_MAX;
4805 for (channel = 0; check_delay > 0 && channel <= max_process_desc; channel++)
4806 {
4807 proc = chan_process[channel];
4808 if (NILP (proc))
4809 continue;
4810 /* Find minimum non-zero read_output_delay among the
4811 processes with non-zero read_output_skip. */
4812 if (XPROCESS (proc)->read_output_delay > 0)
4813 {
4814 check_delay--;
4815 if (!XPROCESS (proc)->read_output_skip)
4816 continue;
4817 FD_CLR (channel, &Available);
4818 XPROCESS (proc)->read_output_skip = 0;
4819 if (XPROCESS (proc)->read_output_delay < usecs)
4820 usecs = XPROCESS (proc)->read_output_delay;
4821 }
4822 }
4823 EMACS_SET_SECS_USECS (timeout, 0, usecs);
4824 process_output_skip = 0;
4825 }
4826 #endif
4827 #ifdef HAVE_NS
4828 nfds = ns_select
4829 #else
4830 nfds = select
4831 #endif
4832 (max (max (max_process_desc, max_keyboard_desc),
4833 max_gpm_desc) + 1,
4834 &Available,
4835 #ifdef NON_BLOCKING_CONNECT
4836 (check_connect ? &Connecting : (SELECT_TYPE *)0),
4837 #else
4838 (SELECT_TYPE *)0,
4839 #endif
4840 (SELECT_TYPE *)0, &timeout);
4841 }
4842
4843 xerrno = errno;
4844
4845 /* Make C-g and alarm signals set flags again */
4846 clear_waiting_for_input ();
4847
4848 /* If we woke up due to SIGWINCH, actually change size now. */
4849 do_pending_window_change (0);
4850
4851 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
4852 /* We wanted the full specified time, so return now. */
4853 break;
4854 if (nfds < 0)
4855 {
4856 if (xerrno == EINTR)
4857 no_avail = 1;
4858 else if (xerrno == EBADF)
4859 {
4860 #ifdef AIX
4861 /* AIX doesn't handle PTY closure the same way BSD does. On AIX,
4862 the child's closure of the pts gives the parent a SIGHUP, and
4863 the ptc file descriptor is automatically closed,
4864 yielding EBADF here or at select() call above.
4865 So, SIGHUP is ignored (see def of PTY_TTY_NAME_SPRINTF
4866 in m/ibmrt-aix.h), and here we just ignore the select error.
4867 Cleanup occurs c/o status_notify after SIGCLD. */
4868 no_avail = 1; /* Cannot depend on values returned */
4869 #else
4870 abort ();
4871 #endif
4872 }
4873 else
4874 error ("select error: %s", emacs_strerror (xerrno));
4875 }
4876
4877 if (no_avail)
4878 {
4879 FD_ZERO (&Available);
4880 IF_NON_BLOCKING_CONNECT (check_connect = 0);
4881 }
4882
4883 #if 0 /* When polling is used, interrupt_input is 0,
4884 so get_input_pending should read the input.
4885 So this should not be needed. */
4886 /* If we are using polling for input,
4887 and we see input available, make it get read now.
4888 Otherwise it might not actually get read for a second.
4889 And on hpux, since we turn off polling in wait_reading_process_output,
4890 it might never get read at all if we don't spend much time
4891 outside of wait_reading_process_output. */
4892 if (read_kbd && interrupt_input
4893 && keyboard_bit_set (&Available)
4894 && input_polling_used ())
4895 kill (getpid (), SIGALRM);
4896 #endif
4897
4898 /* Check for keyboard input */
4899 /* If there is any, return immediately
4900 to give it higher priority than subprocesses */
4901
4902 if (read_kbd != 0)
4903 {
4904 int old_timers_run = timers_run;
4905 struct buffer *old_buffer = current_buffer;
4906 Lisp_Object old_window = selected_window;
4907 int leave = 0;
4908
4909 if (detect_input_pending_run_timers (do_display))
4910 {
4911 swallow_events (do_display);
4912 if (detect_input_pending_run_timers (do_display))
4913 leave = 1;
4914 }
4915
4916 /* If a timer has run, this might have changed buffers
4917 an alike. Make read_key_sequence aware of that. */
4918 if (timers_run != old_timers_run
4919 && waiting_for_user_input_p == -1
4920 && (old_buffer != current_buffer
4921 || !EQ (old_window, selected_window)))
4922 record_asynch_buffer_change ();
4923
4924 if (leave)
4925 break;
4926 }
4927
4928 /* If there is unread keyboard input, also return. */
4929 if (read_kbd != 0
4930 && requeued_events_pending_p ())
4931 break;
4932
4933 /* If we are not checking for keyboard input now,
4934 do process events (but don't run any timers).
4935 This is so that X events will be processed.
4936 Otherwise they may have to wait until polling takes place.
4937 That would causes delays in pasting selections, for example.
4938
4939 (We used to do this only if wait_for_cell.) */
4940 if (read_kbd == 0 && detect_input_pending ())
4941 {
4942 swallow_events (do_display);
4943 #if 0 /* Exiting when read_kbd doesn't request that seems wrong, though. */
4944 if (detect_input_pending ())
4945 break;
4946 #endif
4947 }
4948
4949 /* Exit now if the cell we're waiting for became non-nil. */
4950 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
4951 break;
4952
4953 #ifdef SIGIO
4954 /* If we think we have keyboard input waiting, but didn't get SIGIO,
4955 go read it. This can happen with X on BSD after logging out.
4956 In that case, there really is no input and no SIGIO,
4957 but select says there is input. */
4958
4959 if (read_kbd && interrupt_input
4960 && keyboard_bit_set (&Available) && ! noninteractive)
4961 kill (getpid (), SIGIO);
4962 #endif
4963
4964 if (! wait_proc)
4965 got_some_input |= nfds > 0;
4966
4967 /* If checking input just got us a size-change event from X,
4968 obey it now if we should. */
4969 if (read_kbd || ! NILP (wait_for_cell))
4970 do_pending_window_change (0);
4971
4972 /* Check for data from a process. */
4973 if (no_avail || nfds == 0)
4974 continue;
4975
4976 /* Really FIRST_PROC_DESC should be 0 on Unix,
4977 but this is safer in the short run. */
4978 for (channel = 0; channel <= max_process_desc; channel++)
4979 {
4980 if (FD_ISSET (channel, &Available)
4981 && FD_ISSET (channel, &non_keyboard_wait_mask))
4982 {
4983 int nread;
4984
4985 /* If waiting for this channel, arrange to return as
4986 soon as no more input to be processed. No more
4987 waiting. */
4988 if (wait_channel == channel)
4989 {
4990 wait_channel = -1;
4991 time_limit = -1;
4992 got_some_input = 1;
4993 }
4994 proc = chan_process[channel];
4995 if (NILP (proc))
4996 continue;
4997
4998 /* If this is a server stream socket, accept connection. */
4999 if (EQ (XPROCESS (proc)->status, Qlisten))
5000 {
5001 server_accept_connection (proc, channel);
5002 continue;
5003 }
5004
5005 /* Read data from the process, starting with our
5006 buffered-ahead character if we have one. */
5007
5008 nread = read_process_output (proc, channel);
5009 if (nread > 0)
5010 {
5011 /* Since read_process_output can run a filter,
5012 which can call accept-process-output,
5013 don't try to read from any other processes
5014 before doing the select again. */
5015 FD_ZERO (&Available);
5016
5017 if (do_display)
5018 redisplay_preserve_echo_area (12);
5019 }
5020 #ifdef EWOULDBLOCK
5021 else if (nread == -1 && errno == EWOULDBLOCK)
5022 ;
5023 #endif
5024 /* ISC 4.1 defines both EWOULDBLOCK and O_NONBLOCK,
5025 and Emacs uses O_NONBLOCK, so what we get is EAGAIN. */
5026 #ifdef O_NONBLOCK
5027 else if (nread == -1 && errno == EAGAIN)
5028 ;
5029 #else
5030 #ifdef O_NDELAY
5031 else if (nread == -1 && errno == EAGAIN)
5032 ;
5033 /* Note that we cannot distinguish between no input
5034 available now and a closed pipe.
5035 With luck, a closed pipe will be accompanied by
5036 subprocess termination and SIGCHLD. */
5037 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5038 ;
5039 #endif /* O_NDELAY */
5040 #endif /* O_NONBLOCK */
5041 #ifdef HAVE_PTYS
5042 /* On some OSs with ptys, when the process on one end of
5043 a pty exits, the other end gets an error reading with
5044 errno = EIO instead of getting an EOF (0 bytes read).
5045 Therefore, if we get an error reading and errno =
5046 EIO, just continue, because the child process has
5047 exited and should clean itself up soon (e.g. when we
5048 get a SIGCHLD).
5049
5050 However, it has been known to happen that the SIGCHLD
5051 got lost. So raise the signal again just in case.
5052 It can't hurt. */
5053 else if (nread == -1 && errno == EIO)
5054 {
5055 /* Clear the descriptor now, so we only raise the signal once. */
5056 FD_CLR (channel, &input_wait_mask);
5057 FD_CLR (channel, &non_keyboard_wait_mask);
5058
5059 kill (getpid (), SIGCHLD);
5060 }
5061 #endif /* HAVE_PTYS */
5062 /* If we can detect process termination, don't consider the process
5063 gone just because its pipe is closed. */
5064 #ifdef SIGCHLD
5065 else if (nread == 0 && !NETCONN_P (proc) && !SERIALCONN_P (proc))
5066 ;
5067 #endif
5068 else
5069 {
5070 /* Preserve status of processes already terminated. */
5071 XPROCESS (proc)->tick = ++process_tick;
5072 deactivate_process (proc);
5073 if (XPROCESS (proc)->raw_status_new)
5074 update_status (XPROCESS (proc));
5075 if (EQ (XPROCESS (proc)->status, Qrun))
5076 XPROCESS (proc)->status
5077 = Fcons (Qexit, Fcons (make_number (256), Qnil));
5078 }
5079 }
5080 #ifdef NON_BLOCKING_CONNECT
5081 if (check_connect && FD_ISSET (channel, &Connecting)
5082 && FD_ISSET (channel, &connect_wait_mask))
5083 {
5084 struct Lisp_Process *p;
5085
5086 FD_CLR (channel, &connect_wait_mask);
5087 if (--num_pending_connects < 0)
5088 abort ();
5089
5090 proc = chan_process[channel];
5091 if (NILP (proc))
5092 continue;
5093
5094 p = XPROCESS (proc);
5095
5096 #ifdef GNU_LINUX
5097 /* getsockopt(,,SO_ERROR,,) is said to hang on some systems.
5098 So only use it on systems where it is known to work. */
5099 {
5100 int xlen = sizeof(xerrno);
5101 if (getsockopt(channel, SOL_SOCKET, SO_ERROR, &xerrno, &xlen))
5102 xerrno = errno;
5103 }
5104 #else
5105 {
5106 struct sockaddr pname;
5107 int pnamelen = sizeof(pname);
5108
5109 /* If connection failed, getpeername will fail. */
5110 xerrno = 0;
5111 if (getpeername(channel, &pname, &pnamelen) < 0)
5112 {
5113 /* Obtain connect failure code through error slippage. */
5114 char dummy;
5115 xerrno = errno;
5116 if (errno == ENOTCONN && read(channel, &dummy, 1) < 0)
5117 xerrno = errno;
5118 }
5119 }
5120 #endif
5121 if (xerrno)
5122 {
5123 p->tick = ++process_tick;
5124 p->status = Fcons (Qfailed, Fcons (make_number (xerrno), Qnil));
5125 deactivate_process (proc);
5126 }
5127 else
5128 {
5129 p->status = Qrun;
5130 /* Execute the sentinel here. If we had relied on
5131 status_notify to do it later, it will read input
5132 from the process before calling the sentinel. */
5133 exec_sentinel (proc, build_string ("open\n"));
5134 if (!EQ (p->filter, Qt) && !EQ (p->command, Qt))
5135 {
5136 FD_SET (p->infd, &input_wait_mask);
5137 FD_SET (p->infd, &non_keyboard_wait_mask);
5138 }
5139 }
5140 }
5141 #endif /* NON_BLOCKING_CONNECT */
5142 } /* end for each file descriptor */
5143 } /* end while exit conditions not met */
5144
5145 unbind_to (count, Qnil);
5146
5147 /* If calling from keyboard input, do not quit
5148 since we want to return C-g as an input character.
5149 Otherwise, do pending quit if requested. */
5150 if (read_kbd >= 0)
5151 {
5152 /* Prevent input_pending from remaining set if we quit. */
5153 clear_input_pending ();
5154 QUIT;
5155 }
5156
5157 return got_some_input;
5158 }
5159 \f
5160 /* Given a list (FUNCTION ARGS...), apply FUNCTION to the ARGS. */
5161
5162 static Lisp_Object
5163 read_process_output_call (fun_and_args)
5164 Lisp_Object fun_and_args;
5165 {
5166 return apply1 (XCAR (fun_and_args), XCDR (fun_and_args));
5167 }
5168
5169 static Lisp_Object
5170 read_process_output_error_handler (error)
5171 Lisp_Object error;
5172 {
5173 cmd_error_internal (error, "error in process filter: ");
5174 Vinhibit_quit = Qt;
5175 update_echo_area ();
5176 Fsleep_for (make_number (2), Qnil);
5177 return Qt;
5178 }
5179
5180 /* Read pending output from the process channel,
5181 starting with our buffered-ahead character if we have one.
5182 Yield number of decoded characters read.
5183
5184 This function reads at most 4096 characters.
5185 If you want to read all available subprocess output,
5186 you must call it repeatedly until it returns zero.
5187
5188 The characters read are decoded according to PROC's coding-system
5189 for decoding. */
5190
5191 static int
5192 read_process_output (proc, channel)
5193 Lisp_Object proc;
5194 register int channel;
5195 {
5196 register int nbytes;
5197 char *chars;
5198 register Lisp_Object outstream;
5199 register struct Lisp_Process *p = XPROCESS (proc);
5200 register int opoint;
5201 struct coding_system *coding = proc_decode_coding_system[channel];
5202 int carryover = p->decoding_carryover;
5203 int readmax = 4096;
5204
5205 chars = (char *) alloca (carryover + readmax);
5206 if (carryover)
5207 /* See the comment above. */
5208 bcopy (SDATA (p->decoding_buf), chars, carryover);
5209
5210 #ifdef DATAGRAM_SOCKETS
5211 /* We have a working select, so proc_buffered_char is always -1. */
5212 if (DATAGRAM_CHAN_P (channel))
5213 {
5214 int len = datagram_address[channel].len;
5215 nbytes = recvfrom (channel, chars + carryover, readmax,
5216 0, datagram_address[channel].sa, &len);
5217 }
5218 else
5219 #endif
5220 if (proc_buffered_char[channel] < 0)
5221 {
5222 nbytes = emacs_read (channel, chars + carryover, readmax);
5223 #ifdef ADAPTIVE_READ_BUFFERING
5224 if (nbytes > 0 && p->adaptive_read_buffering)
5225 {
5226 int delay = p->read_output_delay;
5227 if (nbytes < 256)
5228 {
5229 if (delay < READ_OUTPUT_DELAY_MAX_MAX)
5230 {
5231 if (delay == 0)
5232 process_output_delay_count++;
5233 delay += READ_OUTPUT_DELAY_INCREMENT * 2;
5234 }
5235 }
5236 else if (delay > 0 && (nbytes == readmax))
5237 {
5238 delay -= READ_OUTPUT_DELAY_INCREMENT;
5239 if (delay == 0)
5240 process_output_delay_count--;
5241 }
5242 p->read_output_delay = delay;
5243 if (delay)
5244 {
5245 p->read_output_skip = 1;
5246 process_output_skip = 1;
5247 }
5248 }
5249 #endif
5250 }
5251 else
5252 {
5253 chars[carryover] = proc_buffered_char[channel];
5254 proc_buffered_char[channel] = -1;
5255 nbytes = emacs_read (channel, chars + carryover + 1, readmax - 1);
5256 if (nbytes < 0)
5257 nbytes = 1;
5258 else
5259 nbytes = nbytes + 1;
5260 }
5261
5262 p->decoding_carryover = 0;
5263
5264 /* At this point, NBYTES holds number of bytes just received
5265 (including the one in proc_buffered_char[channel]). */
5266 if (nbytes <= 0)
5267 {
5268 if (nbytes < 0 || coding->mode & CODING_MODE_LAST_BLOCK)
5269 return nbytes;
5270 coding->mode |= CODING_MODE_LAST_BLOCK;
5271 }
5272
5273 /* Now set NBYTES how many bytes we must decode. */
5274 nbytes += carryover;
5275
5276 /* Read and dispose of the process output. */
5277 outstream = p->filter;
5278 if (!NILP (outstream))
5279 {
5280 /* We inhibit quit here instead of just catching it so that
5281 hitting ^G when a filter happens to be running won't screw
5282 it up. */
5283 int count = SPECPDL_INDEX ();
5284 Lisp_Object odeactivate;
5285 Lisp_Object obuffer, okeymap;
5286 Lisp_Object text;
5287 int outer_running_asynch_code = running_asynch_code;
5288 int waiting = waiting_for_user_input_p;
5289
5290 /* No need to gcpro these, because all we do with them later
5291 is test them for EQness, and none of them should be a string. */
5292 odeactivate = Vdeactivate_mark;
5293 XSETBUFFER (obuffer, current_buffer);
5294 okeymap = current_buffer->keymap;
5295
5296 specbind (Qinhibit_quit, Qt);
5297 specbind (Qlast_nonmenu_event, Qt);
5298
5299 /* In case we get recursively called,
5300 and we already saved the match data nonrecursively,
5301 save the same match data in safely recursive fashion. */
5302 if (outer_running_asynch_code)
5303 {
5304 Lisp_Object tem;
5305 /* Don't clobber the CURRENT match data, either! */
5306 tem = Fmatch_data (Qnil, Qnil, Qnil);
5307 restore_search_regs ();
5308 record_unwind_save_match_data ();
5309 Fset_match_data (tem, Qt);
5310 }
5311
5312 /* For speed, if a search happens within this code,
5313 save the match data in a special nonrecursive fashion. */
5314 running_asynch_code = 1;
5315
5316 decode_coding_c_string (coding, chars, nbytes, Qt);
5317 text = coding->dst_object;
5318 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5319 /* A new coding system might be found. */
5320 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5321 {
5322 p->decode_coding_system = Vlast_coding_system_used;
5323
5324 /* Don't call setup_coding_system for
5325 proc_decode_coding_system[channel] here. It is done in
5326 detect_coding called via decode_coding above. */
5327
5328 /* If a coding system for encoding is not yet decided, we set
5329 it as the same as coding-system for decoding.
5330
5331 But, before doing that we must check if
5332 proc_encode_coding_system[p->outfd] surely points to a
5333 valid memory because p->outfd will be changed once EOF is
5334 sent to the process. */
5335 if (NILP (p->encode_coding_system)
5336 && proc_encode_coding_system[p->outfd])
5337 {
5338 p->encode_coding_system
5339 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5340 setup_coding_system (p->encode_coding_system,
5341 proc_encode_coding_system[p->outfd]);
5342 }
5343 }
5344
5345 if (coding->carryover_bytes > 0)
5346 {
5347 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5348 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5349 bcopy (coding->carryover, SDATA (p->decoding_buf),
5350 coding->carryover_bytes);
5351 p->decoding_carryover = coding->carryover_bytes;
5352 }
5353 if (SBYTES (text) > 0)
5354 internal_condition_case_1 (read_process_output_call,
5355 Fcons (outstream,
5356 Fcons (proc, Fcons (text, Qnil))),
5357 !NILP (Vdebug_on_error) ? Qnil : Qerror,
5358 read_process_output_error_handler);
5359
5360 /* If we saved the match data nonrecursively, restore it now. */
5361 restore_search_regs ();
5362 running_asynch_code = outer_running_asynch_code;
5363
5364 /* Handling the process output should not deactivate the mark. */
5365 Vdeactivate_mark = odeactivate;
5366
5367 /* Restore waiting_for_user_input_p as it was
5368 when we were called, in case the filter clobbered it. */
5369 waiting_for_user_input_p = waiting;
5370
5371 #if 0 /* Call record_asynch_buffer_change unconditionally,
5372 because we might have changed minor modes or other things
5373 that affect key bindings. */
5374 if (! EQ (Fcurrent_buffer (), obuffer)
5375 || ! EQ (current_buffer->keymap, okeymap))
5376 #endif
5377 /* But do it only if the caller is actually going to read events.
5378 Otherwise there's no need to make him wake up, and it could
5379 cause trouble (for example it would make sit_for return). */
5380 if (waiting_for_user_input_p == -1)
5381 record_asynch_buffer_change ();
5382
5383 unbind_to (count, Qnil);
5384 return nbytes;
5385 }
5386
5387 /* If no filter, write into buffer if it isn't dead. */
5388 if (!NILP (p->buffer) && !NILP (XBUFFER (p->buffer)->name))
5389 {
5390 Lisp_Object old_read_only;
5391 int old_begv, old_zv;
5392 int old_begv_byte, old_zv_byte;
5393 Lisp_Object odeactivate;
5394 int before, before_byte;
5395 int opoint_byte;
5396 Lisp_Object text;
5397 struct buffer *b;
5398 int count = SPECPDL_INDEX ();
5399
5400 odeactivate = Vdeactivate_mark;
5401
5402 record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
5403 Fset_buffer (p->buffer);
5404 opoint = PT;
5405 opoint_byte = PT_BYTE;
5406 old_read_only = current_buffer->read_only;
5407 old_begv = BEGV;
5408 old_zv = ZV;
5409 old_begv_byte = BEGV_BYTE;
5410 old_zv_byte = ZV_BYTE;
5411
5412 current_buffer->read_only = Qnil;
5413
5414 /* Insert new output into buffer
5415 at the current end-of-output marker,
5416 thus preserving logical ordering of input and output. */
5417 if (XMARKER (p->mark)->buffer)
5418 SET_PT_BOTH (clip_to_bounds (BEGV, marker_position (p->mark), ZV),
5419 clip_to_bounds (BEGV_BYTE, marker_byte_position (p->mark),
5420 ZV_BYTE));
5421 else
5422 SET_PT_BOTH (ZV, ZV_BYTE);
5423 before = PT;
5424 before_byte = PT_BYTE;
5425
5426 /* If the output marker is outside of the visible region, save
5427 the restriction and widen. */
5428 if (! (BEGV <= PT && PT <= ZV))
5429 Fwiden ();
5430
5431 decode_coding_c_string (coding, chars, nbytes, Qt);
5432 text = coding->dst_object;
5433 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5434 /* A new coding system might be found. See the comment in the
5435 similar code in the previous `if' block. */
5436 if (!EQ (p->decode_coding_system, Vlast_coding_system_used))
5437 {
5438 p->decode_coding_system = Vlast_coding_system_used;
5439 if (NILP (p->encode_coding_system)
5440 && proc_encode_coding_system[p->outfd])
5441 {
5442 p->encode_coding_system
5443 = coding_inherit_eol_type (Vlast_coding_system_used, Qnil);
5444 setup_coding_system (p->encode_coding_system,
5445 proc_encode_coding_system[p->outfd]);
5446 }
5447 }
5448 if (coding->carryover_bytes > 0)
5449 {
5450 if (SCHARS (p->decoding_buf) < coding->carryover_bytes)
5451 p->decoding_buf = make_uninit_string (coding->carryover_bytes);
5452 bcopy (coding->carryover, SDATA (p->decoding_buf),
5453 coding->carryover_bytes);
5454 p->decoding_carryover = coding->carryover_bytes;
5455 }
5456 /* Adjust the multibyteness of TEXT to that of the buffer. */
5457 if (NILP (current_buffer->enable_multibyte_characters)
5458 != ! STRING_MULTIBYTE (text))
5459 text = (STRING_MULTIBYTE (text)
5460 ? Fstring_as_unibyte (text)
5461 : Fstring_to_multibyte (text));
5462 /* Insert before markers in case we are inserting where
5463 the buffer's mark is, and the user's next command is Meta-y. */
5464 insert_from_string_before_markers (text, 0, 0,
5465 SCHARS (text), SBYTES (text), 0);
5466
5467 /* Make sure the process marker's position is valid when the
5468 process buffer is changed in the signal_after_change above.
5469 W3 is known to do that. */
5470 if (BUFFERP (p->buffer)
5471 && (b = XBUFFER (p->buffer), b != current_buffer))
5472 set_marker_both (p->mark, p->buffer, BUF_PT (b), BUF_PT_BYTE (b));
5473 else
5474 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
5475
5476 update_mode_lines++;
5477
5478 /* Make sure opoint and the old restrictions
5479 float ahead of any new text just as point would. */
5480 if (opoint >= before)
5481 {
5482 opoint += PT - before;
5483 opoint_byte += PT_BYTE - before_byte;
5484 }
5485 if (old_begv > before)
5486 {
5487 old_begv += PT - before;
5488 old_begv_byte += PT_BYTE - before_byte;
5489 }
5490 if (old_zv >= before)
5491 {
5492 old_zv += PT - before;
5493 old_zv_byte += PT_BYTE - before_byte;
5494 }
5495
5496 /* If the restriction isn't what it should be, set it. */
5497 if (old_begv != BEGV || old_zv != ZV)
5498 Fnarrow_to_region (make_number (old_begv), make_number (old_zv));
5499
5500 /* Handling the process output should not deactivate the mark. */
5501 Vdeactivate_mark = odeactivate;
5502
5503 current_buffer->read_only = old_read_only;
5504 SET_PT_BOTH (opoint, opoint_byte);
5505 unbind_to (count, Qnil);
5506 }
5507 return nbytes;
5508 }
5509
5510 DEFUN ("waiting-for-user-input-p", Fwaiting_for_user_input_p, Swaiting_for_user_input_p,
5511 0, 0, 0,
5512 doc: /* Returns non-nil if Emacs is waiting for input from the user.
5513 This is intended for use by asynchronous process output filters and sentinels. */)
5514 ()
5515 {
5516 return (waiting_for_user_input_p ? Qt : Qnil);
5517 }
5518 \f
5519 /* Sending data to subprocess */
5520
5521 jmp_buf send_process_frame;
5522 Lisp_Object process_sent_to;
5523
5524 SIGTYPE
5525 send_process_trap ()
5526 {
5527 SIGNAL_THREAD_CHECK (SIGPIPE);
5528 sigunblock (sigmask (SIGPIPE));
5529 longjmp (send_process_frame, 1);
5530 }
5531
5532 /* Send some data to process PROC.
5533 BUF is the beginning of the data; LEN is the number of characters.
5534 OBJECT is the Lisp object that the data comes from. If OBJECT is
5535 nil or t, it means that the data comes from C string.
5536
5537 If OBJECT is not nil, the data is encoded by PROC's coding-system
5538 for encoding before it is sent.
5539
5540 This function can evaluate Lisp code and can garbage collect. */
5541
5542 static void
5543 send_process (proc, buf, len, object)
5544 volatile Lisp_Object proc;
5545 unsigned char *volatile buf;
5546 volatile int len;
5547 volatile Lisp_Object object;
5548 {
5549 /* Use volatile to protect variables from being clobbered by longjmp. */
5550 struct Lisp_Process *p = XPROCESS (proc);
5551 int rv;
5552 struct coding_system *coding;
5553 struct gcpro gcpro1;
5554 SIGTYPE (*volatile old_sigpipe) ();
5555
5556 GCPRO1 (object);
5557
5558 if (p->raw_status_new)
5559 update_status (p);
5560 if (! EQ (p->status, Qrun))
5561 error ("Process %s not running", SDATA (p->name));
5562 if (p->outfd < 0)
5563 error ("Output file descriptor of %s is closed", SDATA (p->name));
5564
5565 coding = proc_encode_coding_system[p->outfd];
5566 Vlast_coding_system_used = CODING_ID_NAME (coding->id);
5567
5568 if ((STRINGP (object) && STRING_MULTIBYTE (object))
5569 || (BUFFERP (object)
5570 && !NILP (XBUFFER (object)->enable_multibyte_characters))
5571 || EQ (object, Qt))
5572 {
5573 if (!EQ (Vlast_coding_system_used, p->encode_coding_system))
5574 /* The coding system for encoding was changed to raw-text
5575 because we sent a unibyte text previously. Now we are
5576 sending a multibyte text, thus we must encode it by the
5577 original coding system specified for the current process. */
5578 setup_coding_system (p->encode_coding_system, coding);
5579 coding->src_multibyte = 1;
5580 }
5581 else
5582 {
5583 /* For sending a unibyte text, character code conversion should
5584 not take place but EOL conversion should. So, setup raw-text
5585 or one of the subsidiary if we have not yet done it. */
5586 if (CODING_REQUIRE_ENCODING (coding))
5587 {
5588 if (CODING_REQUIRE_FLUSHING (coding))
5589 {
5590 /* But, before changing the coding, we must flush out data. */
5591 coding->mode |= CODING_MODE_LAST_BLOCK;
5592 send_process (proc, "", 0, Qt);
5593 coding->mode &= CODING_MODE_LAST_BLOCK;
5594 }
5595 setup_coding_system (raw_text_coding_system
5596 (Vlast_coding_system_used),
5597 coding);
5598 coding->src_multibyte = 0;
5599 }
5600 }
5601 coding->dst_multibyte = 0;
5602
5603 if (CODING_REQUIRE_ENCODING (coding))
5604 {
5605 coding->dst_object = Qt;
5606 if (BUFFERP (object))
5607 {
5608 int from_byte, from, to;
5609 int save_pt, save_pt_byte;
5610 struct buffer *cur = current_buffer;
5611
5612 set_buffer_internal (XBUFFER (object));
5613 save_pt = PT, save_pt_byte = PT_BYTE;
5614
5615 from_byte = PTR_BYTE_POS (buf);
5616 from = BYTE_TO_CHAR (from_byte);
5617 to = BYTE_TO_CHAR (from_byte + len);
5618 TEMP_SET_PT_BOTH (from, from_byte);
5619 encode_coding_object (coding, object, from, from_byte,
5620 to, from_byte + len, Qt);
5621 TEMP_SET_PT_BOTH (save_pt, save_pt_byte);
5622 set_buffer_internal (cur);
5623 }
5624 else if (STRINGP (object))
5625 {
5626 encode_coding_string (coding, object, 1);
5627 }
5628 else
5629 {
5630 coding->dst_object = make_unibyte_string (buf, len);
5631 coding->produced = len;
5632 }
5633
5634 len = coding->produced;
5635 object = coding->dst_object;
5636 buf = SDATA (object);
5637 }
5638
5639 if (pty_max_bytes == 0)
5640 {
5641 #if defined (HAVE_FPATHCONF) && defined (_PC_MAX_CANON)
5642 pty_max_bytes = fpathconf (p->outfd, _PC_MAX_CANON);
5643 if (pty_max_bytes < 0)
5644 pty_max_bytes = 250;
5645 #else
5646 pty_max_bytes = 250;
5647 #endif
5648 /* Deduct one, to leave space for the eof. */
5649 pty_max_bytes--;
5650 }
5651
5652 /* 2000-09-21: Emacs 20.7, sparc-sun-solaris-2.6, GCC 2.95.2,
5653 CFLAGS="-g -O": The value of the parameter `proc' is clobbered
5654 when returning with longjmp despite being declared volatile. */
5655 if (!setjmp (send_process_frame))
5656 {
5657 process_sent_to = proc;
5658 while (len > 0)
5659 {
5660 int this = len;
5661
5662 /* Decide how much data we can send in one batch.
5663 Long lines need to be split into multiple batches. */
5664 if (p->pty_flag)
5665 {
5666 /* Starting this at zero is always correct when not the first
5667 iteration because the previous iteration ended by sending C-d.
5668 It may not be correct for the first iteration
5669 if a partial line was sent in a separate send_process call.
5670 If that proves worth handling, we need to save linepos
5671 in the process object. */
5672 int linepos = 0;
5673 unsigned char *ptr = (unsigned char *) buf;
5674 unsigned char *end = (unsigned char *) buf + len;
5675
5676 /* Scan through this text for a line that is too long. */
5677 while (ptr != end && linepos < pty_max_bytes)
5678 {
5679 if (*ptr == '\n')
5680 linepos = 0;
5681 else
5682 linepos++;
5683 ptr++;
5684 }
5685 /* If we found one, break the line there
5686 and put in a C-d to force the buffer through. */
5687 this = ptr - buf;
5688 }
5689
5690 /* Send this batch, using one or more write calls. */
5691 while (this > 0)
5692 {
5693 int outfd = p->outfd;
5694 old_sigpipe = (SIGTYPE (*) ()) signal (SIGPIPE, send_process_trap);
5695 #ifdef DATAGRAM_SOCKETS
5696 if (DATAGRAM_CHAN_P (outfd))
5697 {
5698 rv = sendto (outfd, (char *) buf, this,
5699 0, datagram_address[outfd].sa,
5700 datagram_address[outfd].len);
5701 if (rv < 0 && errno == EMSGSIZE)
5702 {
5703 signal (SIGPIPE, old_sigpipe);
5704 report_file_error ("sending datagram",
5705 Fcons (proc, Qnil));
5706 }
5707 }
5708 else
5709 #endif
5710 {
5711 rv = emacs_write (outfd, (char *) buf, this);
5712 #ifdef ADAPTIVE_READ_BUFFERING
5713 if (p->read_output_delay > 0
5714 && p->adaptive_read_buffering == 1)
5715 {
5716 p->read_output_delay = 0;
5717 process_output_delay_count--;
5718 p->read_output_skip = 0;
5719 }
5720 #endif
5721 }
5722 signal (SIGPIPE, old_sigpipe);
5723
5724 if (rv < 0)
5725 {
5726 if (0
5727 #ifdef EWOULDBLOCK
5728 || errno == EWOULDBLOCK
5729 #endif
5730 #ifdef EAGAIN
5731 || errno == EAGAIN
5732 #endif
5733 )
5734 /* Buffer is full. Wait, accepting input;
5735 that may allow the program
5736 to finish doing output and read more. */
5737 {
5738 int offset = 0;
5739
5740 #ifdef BROKEN_PTY_READ_AFTER_EAGAIN
5741 /* A gross hack to work around a bug in FreeBSD.
5742 In the following sequence, read(2) returns
5743 bogus data:
5744
5745 write(2) 1022 bytes
5746 write(2) 954 bytes, get EAGAIN
5747 read(2) 1024 bytes in process_read_output
5748 read(2) 11 bytes in process_read_output
5749
5750 That is, read(2) returns more bytes than have
5751 ever been written successfully. The 1033 bytes
5752 read are the 1022 bytes written successfully
5753 after processing (for example with CRs added if
5754 the terminal is set up that way which it is
5755 here). The same bytes will be seen again in a
5756 later read(2), without the CRs. */
5757
5758 if (errno == EAGAIN)
5759 {
5760 int flags = FWRITE;
5761 ioctl (p->outfd, TIOCFLUSH, &flags);
5762 }
5763 #endif /* BROKEN_PTY_READ_AFTER_EAGAIN */
5764
5765 /* Running filters might relocate buffers or strings.
5766 Arrange to relocate BUF. */
5767 if (BUFFERP (object))
5768 offset = BUF_PTR_BYTE_POS (XBUFFER (object), buf);
5769 else if (STRINGP (object))
5770 offset = buf - SDATA (object);
5771
5772 #ifdef EMACS_HAS_USECS
5773 wait_reading_process_output (0, 20000, 0, 0, Qnil, NULL, 0);
5774 #else
5775 wait_reading_process_output (1, 0, 0, 0, Qnil, NULL, 0);
5776 #endif
5777
5778 if (BUFFERP (object))
5779 buf = BUF_BYTE_ADDRESS (XBUFFER (object), offset);
5780 else if (STRINGP (object))
5781 buf = offset + SDATA (object);
5782
5783 rv = 0;
5784 }
5785 else
5786 /* This is a real error. */
5787 report_file_error ("writing to process", Fcons (proc, Qnil));
5788 }
5789 buf += rv;
5790 len -= rv;
5791 this -= rv;
5792 }
5793
5794 /* If we sent just part of the string, put in an EOF (C-d)
5795 to force it through, before we send the rest. */
5796 if (len > 0)
5797 Fprocess_send_eof (proc);
5798 }
5799 }
5800 else
5801 {
5802 signal (SIGPIPE, old_sigpipe);
5803 proc = process_sent_to;
5804 p = XPROCESS (proc);
5805 p->raw_status_new = 0;
5806 p->status = Fcons (Qexit, Fcons (make_number (256), Qnil));
5807 p->tick = ++process_tick;
5808 deactivate_process (proc);
5809 error ("SIGPIPE raised on process %s; closed it", SDATA (p->name));
5810 }
5811
5812 UNGCPRO;
5813 }
5814
5815 DEFUN ("process-send-region", Fprocess_send_region, Sprocess_send_region,
5816 3, 3, 0,
5817 doc: /* Send current contents of region as input to PROCESS.
5818 PROCESS may be a process, a buffer, the name of a process or buffer, or
5819 nil, indicating the current buffer's process.
5820 Called from program, takes three arguments, PROCESS, START and END.
5821 If the region is more than 500 characters long,
5822 it is sent in several bunches. This may happen even for shorter regions.
5823 Output from processes can arrive in between bunches. */)
5824 (process, start, end)
5825 Lisp_Object process, start, end;
5826 {
5827 Lisp_Object proc;
5828 int start1, end1;
5829
5830 proc = get_process (process);
5831 validate_region (&start, &end);
5832
5833 if (XINT (start) < GPT && XINT (end) > GPT)
5834 move_gap (XINT (start));
5835
5836 start1 = CHAR_TO_BYTE (XINT (start));
5837 end1 = CHAR_TO_BYTE (XINT (end));
5838 send_process (proc, BYTE_POS_ADDR (start1), end1 - start1,
5839 Fcurrent_buffer ());
5840
5841 return Qnil;
5842 }
5843
5844 DEFUN ("process-send-string", Fprocess_send_string, Sprocess_send_string,
5845 2, 2, 0,
5846 doc: /* Send PROCESS the contents of STRING as input.
5847 PROCESS may be a process, a buffer, the name of a process or buffer, or
5848 nil, indicating the current buffer's process.
5849 If STRING is more than 500 characters long,
5850 it is sent in several bunches. This may happen even for shorter strings.
5851 Output from processes can arrive in between bunches. */)
5852 (process, string)
5853 Lisp_Object process, string;
5854 {
5855 Lisp_Object proc;
5856 CHECK_STRING (string);
5857 proc = get_process (process);
5858 send_process (proc, SDATA (string),
5859 SBYTES (string), string);
5860 return Qnil;
5861 }
5862 \f
5863 /* Return the foreground process group for the tty/pty that
5864 the process P uses. */
5865 static int
5866 emacs_get_tty_pgrp (p)
5867 struct Lisp_Process *p;
5868 {
5869 int gid = -1;
5870
5871 #ifdef TIOCGPGRP
5872 if (ioctl (p->infd, TIOCGPGRP, &gid) == -1 && ! NILP (p->tty_name))
5873 {
5874 int fd;
5875 /* Some OS:es (Solaris 8/9) does not allow TIOCGPGRP from the
5876 master side. Try the slave side. */
5877 fd = emacs_open (SDATA (p->tty_name), O_RDONLY, 0);
5878
5879 if (fd != -1)
5880 {
5881 ioctl (fd, TIOCGPGRP, &gid);
5882 emacs_close (fd);
5883 }
5884 }
5885 #endif /* defined (TIOCGPGRP ) */
5886
5887 return gid;
5888 }
5889
5890 DEFUN ("process-running-child-p", Fprocess_running_child_p,
5891 Sprocess_running_child_p, 0, 1, 0,
5892 doc: /* Return t if PROCESS has given the terminal to a child.
5893 If the operating system does not make it possible to find out,
5894 return t unconditionally. */)
5895 (process)
5896 Lisp_Object process;
5897 {
5898 /* Initialize in case ioctl doesn't exist or gives an error,
5899 in a way that will cause returning t. */
5900 int gid;
5901 Lisp_Object proc;
5902 struct Lisp_Process *p;
5903
5904 proc = get_process (process);
5905 p = XPROCESS (proc);
5906
5907 if (!EQ (p->type, Qreal))
5908 error ("Process %s is not a subprocess",
5909 SDATA (p->name));
5910 if (p->infd < 0)
5911 error ("Process %s is not active",
5912 SDATA (p->name));
5913
5914 gid = emacs_get_tty_pgrp (p);
5915
5916 if (gid == p->pid)
5917 return Qnil;
5918 return Qt;
5919 }
5920 \f
5921 /* send a signal number SIGNO to PROCESS.
5922 If CURRENT_GROUP is t, that means send to the process group
5923 that currently owns the terminal being used to communicate with PROCESS.
5924 This is used for various commands in shell mode.
5925 If CURRENT_GROUP is lambda, that means send to the process group
5926 that currently owns the terminal, but only if it is NOT the shell itself.
5927
5928 If NOMSG is zero, insert signal-announcements into process's buffers
5929 right away.
5930
5931 If we can, we try to signal PROCESS by sending control characters
5932 down the pty. This allows us to signal inferiors who have changed
5933 their uid, for which killpg would return an EPERM error. */
5934
5935 static void
5936 process_send_signal (process, signo, current_group, nomsg)
5937 Lisp_Object process;
5938 int signo;
5939 Lisp_Object current_group;
5940 int nomsg;
5941 {
5942 Lisp_Object proc;
5943 register struct Lisp_Process *p;
5944 int gid;
5945 int no_pgrp = 0;
5946
5947 proc = get_process (process);
5948 p = XPROCESS (proc);
5949
5950 if (!EQ (p->type, Qreal))
5951 error ("Process %s is not a subprocess",
5952 SDATA (p->name));
5953 if (p->infd < 0)
5954 error ("Process %s is not active",
5955 SDATA (p->name));
5956
5957 if (!p->pty_flag)
5958 current_group = Qnil;
5959
5960 /* If we are using pgrps, get a pgrp number and make it negative. */
5961 if (NILP (current_group))
5962 /* Send the signal to the shell's process group. */
5963 gid = p->pid;
5964 else
5965 {
5966 #ifdef SIGNALS_VIA_CHARACTERS
5967 /* If possible, send signals to the entire pgrp
5968 by sending an input character to it. */
5969
5970 /* TERMIOS is the latest and bestest, and seems most likely to
5971 work. If the system has it, use it. */
5972 #ifdef HAVE_TERMIOS
5973 struct termios t;
5974 cc_t *sig_char = NULL;
5975
5976 tcgetattr (p->infd, &t);
5977
5978 switch (signo)
5979 {
5980 case SIGINT:
5981 sig_char = &t.c_cc[VINTR];
5982 break;
5983
5984 case SIGQUIT:
5985 sig_char = &t.c_cc[VQUIT];
5986 break;
5987
5988 case SIGTSTP:
5989 #if defined (VSWTCH) && !defined (PREFER_VSUSP)
5990 sig_char = &t.c_cc[VSWTCH];
5991 #else
5992 sig_char = &t.c_cc[VSUSP];
5993 #endif
5994 break;
5995 }
5996
5997 if (sig_char && *sig_char != CDISABLE)
5998 {
5999 send_process (proc, sig_char, 1, Qnil);
6000 return;
6001 }
6002 /* If we can't send the signal with a character,
6003 fall through and send it another way. */
6004 #else /* ! HAVE_TERMIOS */
6005
6006 /* On Berkeley descendants, the following IOCTL's retrieve the
6007 current control characters. */
6008 #if defined (TIOCGLTC) && defined (TIOCGETC)
6009
6010 struct tchars c;
6011 struct ltchars lc;
6012
6013 switch (signo)
6014 {
6015 case SIGINT:
6016 ioctl (p->infd, TIOCGETC, &c);
6017 send_process (proc, &c.t_intrc, 1, Qnil);
6018 return;
6019 case SIGQUIT:
6020 ioctl (p->infd, TIOCGETC, &c);
6021 send_process (proc, &c.t_quitc, 1, Qnil);
6022 return;
6023 #ifdef SIGTSTP
6024 case SIGTSTP:
6025 ioctl (p->infd, TIOCGLTC, &lc);
6026 send_process (proc, &lc.t_suspc, 1, Qnil);
6027 return;
6028 #endif /* ! defined (SIGTSTP) */
6029 }
6030
6031 #else /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6032
6033 /* On SYSV descendants, the TCGETA ioctl retrieves the current control
6034 characters. */
6035 #ifdef TCGETA
6036 struct termio t;
6037 switch (signo)
6038 {
6039 case SIGINT:
6040 ioctl (p->infd, TCGETA, &t);
6041 send_process (proc, &t.c_cc[VINTR], 1, Qnil);
6042 return;
6043 case SIGQUIT:
6044 ioctl (p->infd, TCGETA, &t);
6045 send_process (proc, &t.c_cc[VQUIT], 1, Qnil);
6046 return;
6047 #ifdef SIGTSTP
6048 case SIGTSTP:
6049 ioctl (p->infd, TCGETA, &t);
6050 send_process (proc, &t.c_cc[VSWTCH], 1, Qnil);
6051 return;
6052 #endif /* ! defined (SIGTSTP) */
6053 }
6054 #else /* ! defined (TCGETA) */
6055 Your configuration files are messed up.
6056 /* If your system configuration files define SIGNALS_VIA_CHARACTERS,
6057 you'd better be using one of the alternatives above! */
6058 #endif /* ! defined (TCGETA) */
6059 #endif /* ! defined (TIOCGLTC) && defined (TIOCGETC) */
6060 /* In this case, the code above should alway return. */
6061 abort ();
6062 #endif /* ! defined HAVE_TERMIOS */
6063
6064 /* The code above may fall through if it can't
6065 handle the signal. */
6066 #endif /* defined (SIGNALS_VIA_CHARACTERS) */
6067
6068 #ifdef TIOCGPGRP
6069 /* Get the current pgrp using the tty itself, if we have that.
6070 Otherwise, use the pty to get the pgrp.
6071 On pfa systems, saka@pfu.fujitsu.co.JP writes:
6072 "TIOCGPGRP symbol defined in sys/ioctl.h at E50.
6073 But, TIOCGPGRP does not work on E50 ;-P works fine on E60"
6074 His patch indicates that if TIOCGPGRP returns an error, then
6075 we should just assume that p->pid is also the process group id. */
6076
6077 gid = emacs_get_tty_pgrp (p);
6078
6079 if (gid == -1)
6080 /* If we can't get the information, assume
6081 the shell owns the tty. */
6082 gid = p->pid;
6083
6084 /* It is not clear whether anything really can set GID to -1.
6085 Perhaps on some system one of those ioctls can or could do so.
6086 Or perhaps this is vestigial. */
6087 if (gid == -1)
6088 no_pgrp = 1;
6089 #else /* ! defined (TIOCGPGRP ) */
6090 /* Can't select pgrps on this system, so we know that
6091 the child itself heads the pgrp. */
6092 gid = p->pid;
6093 #endif /* ! defined (TIOCGPGRP ) */
6094
6095 /* If current_group is lambda, and the shell owns the terminal,
6096 don't send any signal. */
6097 if (EQ (current_group, Qlambda) && gid == p->pid)
6098 return;
6099 }
6100
6101 switch (signo)
6102 {
6103 #ifdef SIGCONT
6104 case SIGCONT:
6105 p->raw_status_new = 0;
6106 p->status = Qrun;
6107 p->tick = ++process_tick;
6108 if (!nomsg)
6109 status_notify (NULL);
6110 break;
6111 #endif /* ! defined (SIGCONT) */
6112 case SIGINT:
6113 case SIGQUIT:
6114 case SIGKILL:
6115 flush_pending_output (p->infd);
6116 break;
6117 }
6118
6119 /* If we don't have process groups, send the signal to the immediate
6120 subprocess. That isn't really right, but it's better than any
6121 obvious alternative. */
6122 if (no_pgrp)
6123 {
6124 kill (p->pid, signo);
6125 return;
6126 }
6127
6128 /* gid may be a pid, or minus a pgrp's number */
6129 #ifdef TIOCSIGSEND
6130 if (!NILP (current_group))
6131 {
6132 if (ioctl (p->infd, TIOCSIGSEND, signo) == -1)
6133 EMACS_KILLPG (gid, signo);
6134 }
6135 else
6136 {
6137 gid = - p->pid;
6138 kill (gid, signo);
6139 }
6140 #else /* ! defined (TIOCSIGSEND) */
6141 EMACS_KILLPG (gid, signo);
6142 #endif /* ! defined (TIOCSIGSEND) */
6143 }
6144
6145 DEFUN ("interrupt-process", Finterrupt_process, Sinterrupt_process, 0, 2, 0,
6146 doc: /* Interrupt process PROCESS.
6147 PROCESS may be a process, a buffer, or the name of a process or buffer.
6148 No arg or nil means current buffer's process.
6149 Second arg CURRENT-GROUP non-nil means send signal to
6150 the current process-group of the process's controlling terminal
6151 rather than to the process's own process group.
6152 If the process is a shell, this means interrupt current subjob
6153 rather than the shell.
6154
6155 If CURRENT-GROUP is `lambda', and if the shell owns the terminal,
6156 don't send the signal. */)
6157 (process, current_group)
6158 Lisp_Object process, current_group;
6159 {
6160 process_send_signal (process, SIGINT, current_group, 0);
6161 return process;
6162 }
6163
6164 DEFUN ("kill-process", Fkill_process, Skill_process, 0, 2, 0,
6165 doc: /* Kill process PROCESS. May be process or name of one.
6166 See function `interrupt-process' for more details on usage. */)
6167 (process, current_group)
6168 Lisp_Object process, current_group;
6169 {
6170 process_send_signal (process, SIGKILL, current_group, 0);
6171 return process;
6172 }
6173
6174 DEFUN ("quit-process", Fquit_process, Squit_process, 0, 2, 0,
6175 doc: /* Send QUIT signal to process PROCESS. May be process or name of one.
6176 See function `interrupt-process' for more details on usage. */)
6177 (process, current_group)
6178 Lisp_Object process, current_group;
6179 {
6180 process_send_signal (process, SIGQUIT, current_group, 0);
6181 return process;
6182 }
6183
6184 DEFUN ("stop-process", Fstop_process, Sstop_process, 0, 2, 0,
6185 doc: /* Stop process PROCESS. May be process or name of one.
6186 See function `interrupt-process' for more details on usage.
6187 If PROCESS is a network or serial process, inhibit handling of incoming
6188 traffic. */)
6189 (process, current_group)
6190 Lisp_Object process, current_group;
6191 {
6192 #ifdef HAVE_SOCKETS
6193 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6194 {
6195 struct Lisp_Process *p;
6196
6197 p = XPROCESS (process);
6198 if (NILP (p->command)
6199 && p->infd >= 0)
6200 {
6201 FD_CLR (p->infd, &input_wait_mask);
6202 FD_CLR (p->infd, &non_keyboard_wait_mask);
6203 }
6204 p->command = Qt;
6205 return process;
6206 }
6207 #endif
6208 #ifndef SIGTSTP
6209 error ("No SIGTSTP support");
6210 #else
6211 process_send_signal (process, SIGTSTP, current_group, 0);
6212 #endif
6213 return process;
6214 }
6215
6216 DEFUN ("continue-process", Fcontinue_process, Scontinue_process, 0, 2, 0,
6217 doc: /* Continue process PROCESS. May be process or name of one.
6218 See function `interrupt-process' for more details on usage.
6219 If PROCESS is a network or serial process, resume handling of incoming
6220 traffic. */)
6221 (process, current_group)
6222 Lisp_Object process, current_group;
6223 {
6224 #ifdef HAVE_SOCKETS
6225 if (PROCESSP (process) && (NETCONN_P (process) || SERIALCONN_P (process)))
6226 {
6227 struct Lisp_Process *p;
6228
6229 p = XPROCESS (process);
6230 if (EQ (p->command, Qt)
6231 && p->infd >= 0
6232 && (!EQ (p->filter, Qt) || EQ (p->status, Qlisten)))
6233 {
6234 FD_SET (p->infd, &input_wait_mask);
6235 FD_SET (p->infd, &non_keyboard_wait_mask);
6236 #ifdef WINDOWSNT
6237 if (fd_info[ p->infd ].flags & FILE_SERIAL)
6238 PurgeComm (fd_info[ p->infd ].hnd, PURGE_RXABORT | PURGE_RXCLEAR);
6239 #endif
6240 #ifdef HAVE_TERMIOS
6241 tcflush (p->infd, TCIFLUSH);
6242 #endif
6243 }
6244 p->command = Qnil;
6245 return process;
6246 }
6247 #endif
6248 #ifdef SIGCONT
6249 process_send_signal (process, SIGCONT, current_group, 0);
6250 #else
6251 error ("No SIGCONT support");
6252 #endif
6253 return process;
6254 }
6255
6256 DEFUN ("signal-process", Fsignal_process, Ssignal_process,
6257 2, 2, "sProcess (name or number): \nnSignal code: ",
6258 doc: /* Send PROCESS the signal with code SIGCODE.
6259 PROCESS may also be a number specifying the process id of the
6260 process to signal; in this case, the process need not be a child of
6261 this Emacs.
6262 SIGCODE may be an integer, or a symbol whose name is a signal name. */)
6263 (process, sigcode)
6264 Lisp_Object process, sigcode;
6265 {
6266 pid_t pid;
6267
6268 if (INTEGERP (process))
6269 {
6270 pid = XINT (process);
6271 goto got_it;
6272 }
6273
6274 if (FLOATP (process))
6275 {
6276 pid = (pid_t) XFLOAT_DATA (process);
6277 goto got_it;
6278 }
6279
6280 if (STRINGP (process))
6281 {
6282 Lisp_Object tem;
6283 if (tem = Fget_process (process), NILP (tem))
6284 {
6285 pid = XINT (Fstring_to_number (process, make_number (10)));
6286 if (pid > 0)
6287 goto got_it;
6288 }
6289 process = tem;
6290 }
6291 else
6292 process = get_process (process);
6293
6294 if (NILP (process))
6295 return process;
6296
6297 CHECK_PROCESS (process);
6298 pid = XPROCESS (process)->pid;
6299 if (pid <= 0)
6300 error ("Cannot signal process %s", SDATA (XPROCESS (process)->name));
6301
6302 got_it:
6303
6304 #define parse_signal(NAME, VALUE) \
6305 else if (!xstrcasecmp (name, NAME)) \
6306 XSETINT (sigcode, VALUE)
6307
6308 if (INTEGERP (sigcode))
6309 ;
6310 else
6311 {
6312 unsigned char *name;
6313
6314 CHECK_SYMBOL (sigcode);
6315 name = SDATA (SYMBOL_NAME (sigcode));
6316
6317 if (!strncmp(name, "SIG", 3) || !strncmp(name, "sig", 3))
6318 name += 3;
6319
6320 if (0)
6321 ;
6322 #ifdef SIGUSR1
6323 parse_signal ("usr1", SIGUSR1);
6324 #endif
6325 #ifdef SIGUSR2
6326 parse_signal ("usr2", SIGUSR2);
6327 #endif
6328 #ifdef SIGTERM
6329 parse_signal ("term", SIGTERM);
6330 #endif
6331 #ifdef SIGHUP
6332 parse_signal ("hup", SIGHUP);
6333 #endif
6334 #ifdef SIGINT
6335 parse_signal ("int", SIGINT);
6336 #endif
6337 #ifdef SIGQUIT
6338 parse_signal ("quit", SIGQUIT);
6339 #endif
6340 #ifdef SIGILL
6341 parse_signal ("ill", SIGILL);
6342 #endif
6343 #ifdef SIGABRT
6344 parse_signal ("abrt", SIGABRT);
6345 #endif
6346 #ifdef SIGEMT
6347 parse_signal ("emt", SIGEMT);
6348 #endif
6349 #ifdef SIGKILL
6350 parse_signal ("kill", SIGKILL);
6351 #endif
6352 #ifdef SIGFPE
6353 parse_signal ("fpe", SIGFPE);
6354 #endif
6355 #ifdef SIGBUS
6356 parse_signal ("bus", SIGBUS);
6357 #endif
6358 #ifdef SIGSEGV
6359 parse_signal ("segv", SIGSEGV);
6360 #endif
6361 #ifdef SIGSYS
6362 parse_signal ("sys", SIGSYS);
6363 #endif
6364 #ifdef SIGPIPE
6365 parse_signal ("pipe", SIGPIPE);
6366 #endif
6367 #ifdef SIGALRM
6368 parse_signal ("alrm", SIGALRM);
6369 #endif
6370 #ifdef SIGURG
6371 parse_signal ("urg", SIGURG);
6372 #endif
6373 #ifdef SIGSTOP
6374 parse_signal ("stop", SIGSTOP);
6375 #endif
6376 #ifdef SIGTSTP
6377 parse_signal ("tstp", SIGTSTP);
6378 #endif
6379 #ifdef SIGCONT
6380 parse_signal ("cont", SIGCONT);
6381 #endif
6382 #ifdef SIGCHLD
6383 parse_signal ("chld", SIGCHLD);
6384 #endif
6385 #ifdef SIGTTIN
6386 parse_signal ("ttin", SIGTTIN);
6387 #endif
6388 #ifdef SIGTTOU
6389 parse_signal ("ttou", SIGTTOU);
6390 #endif
6391 #ifdef SIGIO
6392 parse_signal ("io", SIGIO);
6393 #endif
6394 #ifdef SIGXCPU
6395 parse_signal ("xcpu", SIGXCPU);
6396 #endif
6397 #ifdef SIGXFSZ
6398 parse_signal ("xfsz", SIGXFSZ);
6399 #endif
6400 #ifdef SIGVTALRM
6401 parse_signal ("vtalrm", SIGVTALRM);
6402 #endif
6403 #ifdef SIGPROF
6404 parse_signal ("prof", SIGPROF);
6405 #endif
6406 #ifdef SIGWINCH
6407 parse_signal ("winch", SIGWINCH);
6408 #endif
6409 #ifdef SIGINFO
6410 parse_signal ("info", SIGINFO);
6411 #endif
6412 else
6413 error ("Undefined signal name %s", name);
6414 }
6415
6416 #undef parse_signal
6417
6418 return make_number (kill (pid, XINT (sigcode)));
6419 }
6420
6421 DEFUN ("process-send-eof", Fprocess_send_eof, Sprocess_send_eof, 0, 1, 0,
6422 doc: /* Make PROCESS see end-of-file in its input.
6423 EOF comes after any text already sent to it.
6424 PROCESS may be a process, a buffer, the name of a process or buffer, or
6425 nil, indicating the current buffer's process.
6426 If PROCESS is a network connection, or is a process communicating
6427 through a pipe (as opposed to a pty), then you cannot send any more
6428 text to PROCESS after you call this function.
6429 If PROCESS is a serial process, wait until all output written to the
6430 process has been transmitted to the serial port. */)
6431 (process)
6432 Lisp_Object process;
6433 {
6434 Lisp_Object proc;
6435 struct coding_system *coding;
6436
6437 if (DATAGRAM_CONN_P (process))
6438 return process;
6439
6440 proc = get_process (process);
6441 coding = proc_encode_coding_system[XPROCESS (proc)->outfd];
6442
6443 /* Make sure the process is really alive. */
6444 if (XPROCESS (proc)->raw_status_new)
6445 update_status (XPROCESS (proc));
6446 if (! EQ (XPROCESS (proc)->status, Qrun))
6447 error ("Process %s not running", SDATA (XPROCESS (proc)->name));
6448
6449 if (CODING_REQUIRE_FLUSHING (coding))
6450 {
6451 coding->mode |= CODING_MODE_LAST_BLOCK;
6452 send_process (proc, "", 0, Qnil);
6453 }
6454
6455 if (XPROCESS (proc)->pty_flag)
6456 send_process (proc, "\004", 1, Qnil);
6457 else if (EQ (XPROCESS (proc)->type, Qserial))
6458 {
6459 #ifdef HAVE_TERMIOS
6460 if (tcdrain (XPROCESS (proc)->outfd) != 0)
6461 error ("tcdrain() failed: %s", emacs_strerror (errno));
6462 #endif
6463 /* Do nothing on Windows because writes are blocking. */
6464 }
6465 else
6466 {
6467 int old_outfd, new_outfd;
6468
6469 #ifdef HAVE_SHUTDOWN
6470 /* If this is a network connection, or socketpair is used
6471 for communication with the subprocess, call shutdown to cause EOF.
6472 (In some old system, shutdown to socketpair doesn't work.
6473 Then we just can't win.) */
6474 if (EQ (XPROCESS (proc)->type, Qnetwork)
6475 || XPROCESS (proc)->outfd == XPROCESS (proc)->infd)
6476 shutdown (XPROCESS (proc)->outfd, 1);
6477 /* In case of socketpair, outfd == infd, so don't close it. */
6478 if (XPROCESS (proc)->outfd != XPROCESS (proc)->infd)
6479 emacs_close (XPROCESS (proc)->outfd);
6480 #else /* not HAVE_SHUTDOWN */
6481 emacs_close (XPROCESS (proc)->outfd);
6482 #endif /* not HAVE_SHUTDOWN */
6483 new_outfd = emacs_open (NULL_DEVICE, O_WRONLY, 0);
6484 if (new_outfd < 0)
6485 abort ();
6486 old_outfd = XPROCESS (proc)->outfd;
6487
6488 if (!proc_encode_coding_system[new_outfd])
6489 proc_encode_coding_system[new_outfd]
6490 = (struct coding_system *) xmalloc (sizeof (struct coding_system));
6491 bcopy (proc_encode_coding_system[old_outfd],
6492 proc_encode_coding_system[new_outfd],
6493 sizeof (struct coding_system));
6494 bzero (proc_encode_coding_system[old_outfd],
6495 sizeof (struct coding_system));
6496
6497 XPROCESS (proc)->outfd = new_outfd;
6498 }
6499 return process;
6500 }
6501
6502 /* Kill all processes associated with `buffer'.
6503 If `buffer' is nil, kill all processes */
6504
6505 void
6506 kill_buffer_processes (buffer)
6507 Lisp_Object buffer;
6508 {
6509 Lisp_Object tail, proc;
6510
6511 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6512 {
6513 proc = XCDR (XCAR (tail));
6514 if (PROCESSP (proc)
6515 && (NILP (buffer) || EQ (XPROCESS (proc)->buffer, buffer)))
6516 {
6517 if (NETCONN_P (proc) || SERIALCONN_P (proc))
6518 Fdelete_process (proc);
6519 else if (XPROCESS (proc)->infd >= 0)
6520 process_send_signal (proc, SIGHUP, Qnil, 1);
6521 }
6522 }
6523 }
6524 \f
6525 /* On receipt of a signal that a child status has changed, loop asking
6526 about children with changed statuses until the system says there
6527 are no more.
6528
6529 All we do is change the status; we do not run sentinels or print
6530 notifications. That is saved for the next time keyboard input is
6531 done, in order to avoid timing errors.
6532
6533 ** WARNING: this can be called during garbage collection.
6534 Therefore, it must not be fooled by the presence of mark bits in
6535 Lisp objects.
6536
6537 ** USG WARNING: Although it is not obvious from the documentation
6538 in signal(2), on a USG system the SIGCLD handler MUST NOT call
6539 signal() before executing at least one wait(), otherwise the
6540 handler will be called again, resulting in an infinite loop. The
6541 relevant portion of the documentation reads "SIGCLD signals will be
6542 queued and the signal-catching function will be continually
6543 reentered until the queue is empty". Invoking signal() causes the
6544 kernel to reexamine the SIGCLD queue. Fred Fish, UniSoft Systems
6545 Inc.
6546
6547 ** Malloc WARNING: This should never call malloc either directly or
6548 indirectly; if it does, that is a bug */
6549
6550 #ifdef SIGCHLD
6551 SIGTYPE
6552 sigchld_handler (signo)
6553 int signo;
6554 {
6555 int old_errno = errno;
6556 Lisp_Object proc;
6557 register struct Lisp_Process *p;
6558 extern EMACS_TIME *input_available_clear_time;
6559
6560 SIGNAL_THREAD_CHECK (signo);
6561
6562 while (1)
6563 {
6564 pid_t pid;
6565 int w;
6566 Lisp_Object tail;
6567
6568 #ifdef WNOHANG
6569 #ifndef WUNTRACED
6570 #define WUNTRACED 0
6571 #endif /* no WUNTRACED */
6572 /* Keep trying to get a status until we get a definitive result. */
6573 do
6574 {
6575 errno = 0;
6576 pid = wait3 (&w, WNOHANG | WUNTRACED, 0);
6577 }
6578 while (pid < 0 && errno == EINTR);
6579
6580 if (pid <= 0)
6581 {
6582 /* PID == 0 means no processes found, PID == -1 means a real
6583 failure. We have done all our job, so return. */
6584
6585 /* USG systems forget handlers when they are used;
6586 must reestablish each time */
6587 #if defined (USG) && !defined (POSIX_SIGNALS)
6588 signal (signo, sigchld_handler); /* WARNING - must come after wait3() */
6589 #endif
6590 errno = old_errno;
6591 return;
6592 }
6593 #else
6594 pid = wait (&w);
6595 #endif /* no WNOHANG */
6596
6597 /* Find the process that signaled us, and record its status. */
6598
6599 /* The process can have been deleted by Fdelete_process. */
6600 for (tail = deleted_pid_list; CONSP (tail); tail = XCDR (tail))
6601 {
6602 Lisp_Object xpid = XCAR (tail);
6603 if ((INTEGERP (xpid) && pid == (pid_t) XINT (xpid))
6604 || (FLOATP (xpid) && pid == (pid_t) XFLOAT_DATA (xpid)))
6605 {
6606 XSETCAR (tail, Qnil);
6607 goto sigchld_end_of_loop;
6608 }
6609 }
6610
6611 /* Otherwise, if it is asynchronous, it is in Vprocess_alist. */
6612 p = 0;
6613 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6614 {
6615 proc = XCDR (XCAR (tail));
6616 p = XPROCESS (proc);
6617 if (EQ (p->type, Qreal) && p->pid == pid)
6618 break;
6619 p = 0;
6620 }
6621
6622 /* Look for an asynchronous process whose pid hasn't been filled
6623 in yet. */
6624 if (p == 0)
6625 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6626 {
6627 proc = XCDR (XCAR (tail));
6628 p = XPROCESS (proc);
6629 if (p->pid == -1)
6630 break;
6631 p = 0;
6632 }
6633
6634 /* Change the status of the process that was found. */
6635 if (p != 0)
6636 {
6637 int clear_desc_flag = 0;
6638
6639 p->tick = ++process_tick;
6640 p->raw_status = w;
6641 p->raw_status_new = 1;
6642
6643 /* If process has terminated, stop waiting for its output. */
6644 if ((WIFSIGNALED (w) || WIFEXITED (w))
6645 && p->infd >= 0)
6646 clear_desc_flag = 1;
6647
6648 /* We use clear_desc_flag to avoid a compiler bug in Microsoft C. */
6649 if (clear_desc_flag)
6650 {
6651 FD_CLR (p->infd, &input_wait_mask);
6652 FD_CLR (p->infd, &non_keyboard_wait_mask);
6653 }
6654
6655 /* Tell wait_reading_process_output that it needs to wake up and
6656 look around. */
6657 if (input_available_clear_time)
6658 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6659 }
6660
6661 /* There was no asynchronous process found for that pid: we have
6662 a synchronous process. */
6663 else
6664 {
6665 synch_process_alive = 0;
6666
6667 /* Report the status of the synchronous process. */
6668 if (WIFEXITED (w))
6669 synch_process_retcode = WRETCODE (w);
6670 else if (WIFSIGNALED (w))
6671 synch_process_termsig = WTERMSIG (w);
6672
6673 /* Tell wait_reading_process_output that it needs to wake up and
6674 look around. */
6675 if (input_available_clear_time)
6676 EMACS_SET_SECS_USECS (*input_available_clear_time, 0, 0);
6677 }
6678
6679 sigchld_end_of_loop:
6680 ;
6681
6682 /* On some systems, we must return right away.
6683 If any more processes want to signal us, we will
6684 get another signal.
6685 Otherwise (on systems that have WNOHANG), loop around
6686 to use up all the processes that have something to tell us. */
6687 #if (defined WINDOWSNT \
6688 || (defined USG && !defined GNU_LINUX \
6689 && !(defined HPUX && defined WNOHANG)))
6690 #if defined (USG) && ! defined (POSIX_SIGNALS)
6691 signal (signo, sigchld_handler);
6692 #endif
6693 errno = old_errno;
6694 return;
6695 #endif /* USG, but not HPUX with WNOHANG */
6696 }
6697 }
6698 #endif /* SIGCHLD */
6699 \f
6700
6701 static Lisp_Object
6702 exec_sentinel_unwind (data)
6703 Lisp_Object data;
6704 {
6705 XPROCESS (XCAR (data))->sentinel = XCDR (data);
6706 return Qnil;
6707 }
6708
6709 static Lisp_Object
6710 exec_sentinel_error_handler (error)
6711 Lisp_Object error;
6712 {
6713 cmd_error_internal (error, "error in process sentinel: ");
6714 Vinhibit_quit = Qt;
6715 update_echo_area ();
6716 Fsleep_for (make_number (2), Qnil);
6717 return Qt;
6718 }
6719
6720 static void
6721 exec_sentinel (proc, reason)
6722 Lisp_Object proc, reason;
6723 {
6724 Lisp_Object sentinel, obuffer, odeactivate, okeymap;
6725 register struct Lisp_Process *p = XPROCESS (proc);
6726 int count = SPECPDL_INDEX ();
6727 int outer_running_asynch_code = running_asynch_code;
6728 int waiting = waiting_for_user_input_p;
6729
6730 if (inhibit_sentinels)
6731 return;
6732
6733 /* No need to gcpro these, because all we do with them later
6734 is test them for EQness, and none of them should be a string. */
6735 odeactivate = Vdeactivate_mark;
6736 XSETBUFFER (obuffer, current_buffer);
6737 okeymap = current_buffer->keymap;
6738
6739 sentinel = p->sentinel;
6740 if (NILP (sentinel))
6741 return;
6742
6743 /* Zilch the sentinel while it's running, to avoid recursive invocations;
6744 assure that it gets restored no matter how the sentinel exits. */
6745 p->sentinel = Qnil;
6746 record_unwind_protect (exec_sentinel_unwind, Fcons (proc, sentinel));
6747 /* Inhibit quit so that random quits don't screw up a running filter. */
6748 specbind (Qinhibit_quit, Qt);
6749 specbind (Qlast_nonmenu_event, Qt);
6750
6751 /* In case we get recursively called,
6752 and we already saved the match data nonrecursively,
6753 save the same match data in safely recursive fashion. */
6754 if (outer_running_asynch_code)
6755 {
6756 Lisp_Object tem;
6757 tem = Fmatch_data (Qnil, Qnil, Qnil);
6758 restore_search_regs ();
6759 record_unwind_save_match_data ();
6760 Fset_match_data (tem, Qt);
6761 }
6762
6763 /* For speed, if a search happens within this code,
6764 save the match data in a special nonrecursive fashion. */
6765 running_asynch_code = 1;
6766
6767 internal_condition_case_1 (read_process_output_call,
6768 Fcons (sentinel,
6769 Fcons (proc, Fcons (reason, Qnil))),
6770 !NILP (Vdebug_on_error) ? Qnil : Qerror,
6771 exec_sentinel_error_handler);
6772
6773 /* If we saved the match data nonrecursively, restore it now. */
6774 restore_search_regs ();
6775 running_asynch_code = outer_running_asynch_code;
6776
6777 Vdeactivate_mark = odeactivate;
6778
6779 /* Restore waiting_for_user_input_p as it was
6780 when we were called, in case the filter clobbered it. */
6781 waiting_for_user_input_p = waiting;
6782
6783 #if 0
6784 if (! EQ (Fcurrent_buffer (), obuffer)
6785 || ! EQ (current_buffer->keymap, okeymap))
6786 #endif
6787 /* But do it only if the caller is actually going to read events.
6788 Otherwise there's no need to make him wake up, and it could
6789 cause trouble (for example it would make sit_for return). */
6790 if (waiting_for_user_input_p == -1)
6791 record_asynch_buffer_change ();
6792
6793 unbind_to (count, Qnil);
6794 }
6795
6796 /* Report all recent events of a change in process status
6797 (either run the sentinel or output a message).
6798 This is usually done while Emacs is waiting for keyboard input
6799 but can be done at other times. */
6800
6801 static void
6802 status_notify (deleting_process)
6803 struct Lisp_Process *deleting_process;
6804 {
6805 register Lisp_Object proc, buffer;
6806 Lisp_Object tail, msg;
6807 struct gcpro gcpro1, gcpro2;
6808
6809 tail = Qnil;
6810 msg = Qnil;
6811 /* We need to gcpro tail; if read_process_output calls a filter
6812 which deletes a process and removes the cons to which tail points
6813 from Vprocess_alist, and then causes a GC, tail is an unprotected
6814 reference. */
6815 GCPRO2 (tail, msg);
6816
6817 /* Set this now, so that if new processes are created by sentinels
6818 that we run, we get called again to handle their status changes. */
6819 update_tick = process_tick;
6820
6821 for (tail = Vprocess_alist; CONSP (tail); tail = XCDR (tail))
6822 {
6823 Lisp_Object symbol;
6824 register struct Lisp_Process *p;
6825
6826 proc = Fcdr (XCAR (tail));
6827 p = XPROCESS (proc);
6828
6829 if (p->tick != p->update_tick)
6830 {
6831 p->update_tick = p->tick;
6832
6833 /* If process is still active, read any output that remains. */
6834 while (! EQ (p->filter, Qt)
6835 && ! EQ (p->status, Qconnect)
6836 && ! EQ (p->status, Qlisten)
6837 /* Network or serial process not stopped: */
6838 && ! EQ (p->command, Qt)
6839 && p->infd >= 0
6840 && p != deleting_process
6841 && read_process_output (proc, p->infd) > 0);
6842
6843 buffer = p->buffer;
6844
6845 /* Get the text to use for the message. */
6846 if (p->raw_status_new)
6847 update_status (p);
6848 msg = status_message (p);
6849
6850 /* If process is terminated, deactivate it or delete it. */
6851 symbol = p->status;
6852 if (CONSP (p->status))
6853 symbol = XCAR (p->status);
6854
6855 if (EQ (symbol, Qsignal) || EQ (symbol, Qexit)
6856 || EQ (symbol, Qclosed))
6857 {
6858 if (delete_exited_processes)
6859 remove_process (proc);
6860 else
6861 deactivate_process (proc);
6862 }
6863
6864 /* The actions above may have further incremented p->tick.
6865 So set p->update_tick again
6866 so that an error in the sentinel will not cause
6867 this code to be run again. */
6868 p->update_tick = p->tick;
6869 /* Now output the message suitably. */
6870 if (!NILP (p->sentinel))
6871 exec_sentinel (proc, msg);
6872 /* Don't bother with a message in the buffer
6873 when a process becomes runnable. */
6874 else if (!EQ (symbol, Qrun) && !NILP (buffer))
6875 {
6876 Lisp_Object ro, tem;
6877 struct buffer *old = current_buffer;
6878 int opoint, opoint_byte;
6879 int before, before_byte;
6880
6881 ro = XBUFFER (buffer)->read_only;
6882
6883 /* Avoid error if buffer is deleted
6884 (probably that's why the process is dead, too) */
6885 if (NILP (XBUFFER (buffer)->name))
6886 continue;
6887 Fset_buffer (buffer);
6888
6889 opoint = PT;
6890 opoint_byte = PT_BYTE;
6891 /* Insert new output into buffer
6892 at the current end-of-output marker,
6893 thus preserving logical ordering of input and output. */
6894 if (XMARKER (p->mark)->buffer)
6895 Fgoto_char (p->mark);
6896 else
6897 SET_PT_BOTH (ZV, ZV_BYTE);
6898
6899 before = PT;
6900 before_byte = PT_BYTE;
6901
6902 tem = current_buffer->read_only;
6903 current_buffer->read_only = Qnil;
6904 insert_string ("\nProcess ");
6905 Finsert (1, &p->name);
6906 insert_string (" ");
6907 Finsert (1, &msg);
6908 current_buffer->read_only = tem;
6909 set_marker_both (p->mark, p->buffer, PT, PT_BYTE);
6910
6911 if (opoint >= before)
6912 SET_PT_BOTH (opoint + (PT - before),
6913 opoint_byte + (PT_BYTE - before_byte));
6914 else
6915 SET_PT_BOTH (opoint, opoint_byte);
6916
6917 set_buffer_internal (old);
6918 }
6919 }
6920 } /* end for */
6921
6922 update_mode_lines++; /* in case buffers use %s in mode-line-format */
6923 redisplay_preserve_echo_area (13);
6924
6925 UNGCPRO;
6926 }
6927
6928 \f
6929 DEFUN ("set-process-coding-system", Fset_process_coding_system,
6930 Sset_process_coding_system, 1, 3, 0,
6931 doc: /* Set coding systems of PROCESS to DECODING and ENCODING.
6932 DECODING will be used to decode subprocess output and ENCODING to
6933 encode subprocess input. */)
6934 (process, decoding, encoding)
6935 register Lisp_Object process, decoding, encoding;
6936 {
6937 register struct Lisp_Process *p;
6938
6939 CHECK_PROCESS (process);
6940 p = XPROCESS (process);
6941 if (p->infd < 0)
6942 error ("Input file descriptor of %s closed", SDATA (p->name));
6943 if (p->outfd < 0)
6944 error ("Output file descriptor of %s closed", SDATA (p->name));
6945 Fcheck_coding_system (decoding);
6946 Fcheck_coding_system (encoding);
6947 encoding = coding_inherit_eol_type (encoding, Qnil);
6948 p->decode_coding_system = decoding;
6949 p->encode_coding_system = encoding;
6950 setup_process_coding_systems (process);
6951
6952 return Qnil;
6953 }
6954
6955 DEFUN ("process-coding-system",
6956 Fprocess_coding_system, Sprocess_coding_system, 1, 1, 0,
6957 doc: /* Return a cons of coding systems for decoding and encoding of PROCESS. */)
6958 (process)
6959 register Lisp_Object process;
6960 {
6961 CHECK_PROCESS (process);
6962 return Fcons (XPROCESS (process)->decode_coding_system,
6963 XPROCESS (process)->encode_coding_system);
6964 }
6965
6966 DEFUN ("set-process-filter-multibyte", Fset_process_filter_multibyte,
6967 Sset_process_filter_multibyte, 2, 2, 0,
6968 doc: /* Set multibyteness of the strings given to PROCESS's filter.
6969 If FLAG is non-nil, the filter is given multibyte strings.
6970 If FLAG is nil, the filter is given unibyte strings. In this case,
6971 all character code conversion except for end-of-line conversion is
6972 suppressed. */)
6973 (process, flag)
6974 Lisp_Object process, flag;
6975 {
6976 register struct Lisp_Process *p;
6977
6978 CHECK_PROCESS (process);
6979 p = XPROCESS (process);
6980 if (NILP (flag))
6981 p->decode_coding_system = raw_text_coding_system (p->decode_coding_system);
6982 setup_process_coding_systems (process);
6983
6984 return Qnil;
6985 }
6986
6987 DEFUN ("process-filter-multibyte-p", Fprocess_filter_multibyte_p,
6988 Sprocess_filter_multibyte_p, 1, 1, 0,
6989 doc: /* Return t if a multibyte string is given to PROCESS's filter.*/)
6990 (process)
6991 Lisp_Object process;
6992 {
6993 register struct Lisp_Process *p;
6994 struct coding_system *coding;
6995
6996 CHECK_PROCESS (process);
6997 p = XPROCESS (process);
6998 coding = proc_decode_coding_system[p->infd];
6999 return (CODING_FOR_UNIBYTE (coding) ? Qnil : Qt);
7000 }
7001
7002
7003 \f
7004 /* Add DESC to the set of keyboard input descriptors. */
7005
7006 void
7007 add_keyboard_wait_descriptor (desc)
7008 int desc;
7009 {
7010 FD_SET (desc, &input_wait_mask);
7011 FD_SET (desc, &non_process_wait_mask);
7012 if (desc > max_keyboard_desc)
7013 max_keyboard_desc = desc;
7014 }
7015
7016 static int add_gpm_wait_descriptor_called_flag;
7017
7018 void
7019 add_gpm_wait_descriptor (desc)
7020 int desc;
7021 {
7022 if (! add_gpm_wait_descriptor_called_flag)
7023 FD_CLR (0, &input_wait_mask);
7024 add_gpm_wait_descriptor_called_flag = 1;
7025 FD_SET (desc, &input_wait_mask);
7026 FD_SET (desc, &gpm_wait_mask);
7027 if (desc > max_gpm_desc)
7028 max_gpm_desc = desc;
7029 }
7030
7031 /* From now on, do not expect DESC to give keyboard input. */
7032
7033 void
7034 delete_keyboard_wait_descriptor (desc)
7035 int desc;
7036 {
7037 int fd;
7038 int lim = max_keyboard_desc;
7039
7040 FD_CLR (desc, &input_wait_mask);
7041 FD_CLR (desc, &non_process_wait_mask);
7042
7043 if (desc == max_keyboard_desc)
7044 for (fd = 0; fd < lim; fd++)
7045 if (FD_ISSET (fd, &input_wait_mask)
7046 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7047 && !FD_ISSET (fd, &gpm_wait_mask))
7048 max_keyboard_desc = fd;
7049 }
7050
7051 void
7052 delete_gpm_wait_descriptor (desc)
7053 int desc;
7054 {
7055 int fd;
7056 int lim = max_gpm_desc;
7057
7058 FD_CLR (desc, &input_wait_mask);
7059 FD_CLR (desc, &non_process_wait_mask);
7060
7061 if (desc == max_gpm_desc)
7062 for (fd = 0; fd < lim; fd++)
7063 if (FD_ISSET (fd, &input_wait_mask)
7064 && !FD_ISSET (fd, &non_keyboard_wait_mask)
7065 && !FD_ISSET (fd, &non_process_wait_mask))
7066 max_gpm_desc = fd;
7067 }
7068
7069 /* Return nonzero if *MASK has a bit set
7070 that corresponds to one of the keyboard input descriptors. */
7071
7072 static int
7073 keyboard_bit_set (mask)
7074 SELECT_TYPE *mask;
7075 {
7076 int fd;
7077
7078 for (fd = 0; fd <= max_keyboard_desc; fd++)
7079 if (FD_ISSET (fd, mask) && FD_ISSET (fd, &input_wait_mask)
7080 && !FD_ISSET (fd, &non_keyboard_wait_mask))
7081 return 1;
7082
7083 return 0;
7084 }
7085 \f
7086 /* Enumeration of and access to system processes a-la ps(1). */
7087
7088 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7089 0, 0, 0,
7090 doc: /* Return a list of numerical process IDs of all running processes.
7091 If this functionality is unsupported, return nil.
7092
7093 See `process-attributes' for getting attributes of a process given its ID. */)
7094 ()
7095 {
7096 return list_system_processes ();
7097 }
7098
7099 DEFUN ("process-attributes", Fprocess_attributes,
7100 Sprocess_attributes, 1, 1, 0,
7101 doc: /* Return attributes of the process given by its PID, a number.
7102
7103 Value is an alist where each element is a cons cell of the form
7104
7105 \(KEY . VALUE)
7106
7107 If this functionality is unsupported, the value is nil.
7108
7109 See `list-system-processes' for getting a list of all process IDs.
7110
7111 The KEYs of the attributes that this function may return are listed
7112 below, together with the type of the associated VALUE (in parentheses).
7113 Not all platforms support all of these attributes; unsupported
7114 attributes will not appear in the returned alist.
7115 Unless explicitly indicated otherwise, numbers can have either
7116 integer or floating point values.
7117
7118 euid -- Effective user User ID of the process (number)
7119 user -- User name corresponding to euid (string)
7120 egid -- Effective user Group ID of the process (number)
7121 group -- Group name corresponding to egid (string)
7122 comm -- Command name (executable name only) (string)
7123 state -- Process state code, such as "S", "R", or "T" (string)
7124 ppid -- Parent process ID (number)
7125 pgrp -- Process group ID (number)
7126 sess -- Session ID, i.e. process ID of session leader (number)
7127 ttname -- Controlling tty name (string)
7128 tpgid -- ID of foreground process group on the process's tty (number)
7129 minflt -- number of minor page faults (number)
7130 majflt -- number of major page faults (number)
7131 cminflt -- cumulative number of minor page faults (number)
7132 cmajflt -- cumulative number of major page faults (number)
7133 utime -- user time used by the process, in the (HIGH LOW USEC) format
7134 stime -- system time used by the process, in the (HIGH LOW USEC) format
7135 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7136 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7137 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7138 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7139 pri -- priority of the process (number)
7140 nice -- nice value of the process (number)
7141 thcount -- process thread count (number)
7142 start -- time the process started, in the (HIGH LOW USEC) format
7143 vsize -- virtual memory size of the process in KB's (number)
7144 rss -- resident set size of the process in KB's (number)
7145 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7146 pcpu -- percents of CPU time used by the process (floating-point number)
7147 pmem -- percents of total physical memory used by process's resident set
7148 (floating-point number)
7149 args -- command line which invoked the process (string). */)
7150 (pid)
7151
7152 Lisp_Object pid;
7153 {
7154 return system_process_attributes (pid);
7155 }
7156 \f
7157 void
7158 init_process ()
7159 {
7160 register int i;
7161
7162 inhibit_sentinels = 0;
7163
7164 #ifdef SIGCHLD
7165 #ifndef CANNOT_DUMP
7166 if (! noninteractive || initialized)
7167 #endif
7168 signal (SIGCHLD, sigchld_handler);
7169 #endif
7170
7171 FD_ZERO (&input_wait_mask);
7172 FD_ZERO (&non_keyboard_wait_mask);
7173 FD_ZERO (&non_process_wait_mask);
7174 max_process_desc = 0;
7175
7176 #ifdef NON_BLOCKING_CONNECT
7177 FD_ZERO (&connect_wait_mask);
7178 num_pending_connects = 0;
7179 #endif
7180
7181 #ifdef ADAPTIVE_READ_BUFFERING
7182 process_output_delay_count = 0;
7183 process_output_skip = 0;
7184 #endif
7185
7186 /* Don't do this, it caused infinite select loops. The display
7187 method should call add_keyboard_wait_descriptor on stdin if it
7188 needs that. */
7189 #if 0
7190 FD_SET (0, &input_wait_mask);
7191 #endif
7192
7193 Vprocess_alist = Qnil;
7194 #ifdef SIGCHLD
7195 deleted_pid_list = Qnil;
7196 #endif
7197 for (i = 0; i < MAXDESC; i++)
7198 {
7199 chan_process[i] = Qnil;
7200 proc_buffered_char[i] = -1;
7201 }
7202 bzero (proc_decode_coding_system, sizeof proc_decode_coding_system);
7203 bzero (proc_encode_coding_system, sizeof proc_encode_coding_system);
7204 #ifdef DATAGRAM_SOCKETS
7205 bzero (datagram_address, sizeof datagram_address);
7206 #endif
7207
7208 #ifdef HAVE_SOCKETS
7209 {
7210 Lisp_Object subfeatures = Qnil;
7211 struct socket_options *sopt;
7212
7213 #define ADD_SUBFEATURE(key, val) \
7214 subfeatures = Fcons (Fcons (key, Fcons (val, Qnil)), subfeatures)
7215
7216 #ifdef NON_BLOCKING_CONNECT
7217 ADD_SUBFEATURE (QCnowait, Qt);
7218 #endif
7219 #ifdef DATAGRAM_SOCKETS
7220 ADD_SUBFEATURE (QCtype, Qdatagram);
7221 #endif
7222 #ifdef HAVE_LOCAL_SOCKETS
7223 ADD_SUBFEATURE (QCfamily, Qlocal);
7224 #endif
7225 ADD_SUBFEATURE (QCfamily, Qipv4);
7226 #ifdef AF_INET6
7227 ADD_SUBFEATURE (QCfamily, Qipv6);
7228 #endif
7229 #ifdef HAVE_GETSOCKNAME
7230 ADD_SUBFEATURE (QCservice, Qt);
7231 #endif
7232 #if defined(O_NONBLOCK) || defined(O_NDELAY)
7233 ADD_SUBFEATURE (QCserver, Qt);
7234 #endif
7235
7236 for (sopt = socket_options; sopt->name; sopt++)
7237 subfeatures = Fcons (intern (sopt->name), subfeatures);
7238
7239 Fprovide (intern ("make-network-process"), subfeatures);
7240 }
7241 #endif /* HAVE_SOCKETS */
7242
7243 #if defined (DARWIN_OS)
7244 /* PTYs are broken on Darwin < 6, but are sometimes useful for interactive
7245 processes. As such, we only change the default value. */
7246 if (initialized)
7247 {
7248 char *release = get_operating_system_release();
7249 if (!release || !release[0] || (release[0] < MIN_PTY_KERNEL_VERSION
7250 && release[1] == '.')) {
7251 Vprocess_connection_type = Qnil;
7252 }
7253 }
7254 #endif
7255 }
7256
7257 void
7258 syms_of_process ()
7259 {
7260 Qprocessp = intern ("processp");
7261 staticpro (&Qprocessp);
7262 Qrun = intern ("run");
7263 staticpro (&Qrun);
7264 Qstop = intern ("stop");
7265 staticpro (&Qstop);
7266 Qsignal = intern ("signal");
7267 staticpro (&Qsignal);
7268
7269 /* Qexit is already staticpro'd by syms_of_eval; don't staticpro it
7270 here again.
7271
7272 Qexit = intern ("exit");
7273 staticpro (&Qexit); */
7274
7275 Qopen = intern ("open");
7276 staticpro (&Qopen);
7277 Qclosed = intern ("closed");
7278 staticpro (&Qclosed);
7279 Qconnect = intern ("connect");
7280 staticpro (&Qconnect);
7281 Qfailed = intern ("failed");
7282 staticpro (&Qfailed);
7283 Qlisten = intern ("listen");
7284 staticpro (&Qlisten);
7285 Qlocal = intern ("local");
7286 staticpro (&Qlocal);
7287 Qipv4 = intern ("ipv4");
7288 staticpro (&Qipv4);
7289 #ifdef AF_INET6
7290 Qipv6 = intern ("ipv6");
7291 staticpro (&Qipv6);
7292 #endif
7293 Qdatagram = intern ("datagram");
7294 staticpro (&Qdatagram);
7295
7296 QCport = intern (":port");
7297 staticpro (&QCport);
7298 QCspeed = intern (":speed");
7299 staticpro (&QCspeed);
7300 QCprocess = intern (":process");
7301 staticpro (&QCprocess);
7302
7303 QCbytesize = intern (":bytesize");
7304 staticpro (&QCbytesize);
7305 QCstopbits = intern (":stopbits");
7306 staticpro (&QCstopbits);
7307 QCparity = intern (":parity");
7308 staticpro (&QCparity);
7309 Qodd = intern ("odd");
7310 staticpro (&Qodd);
7311 Qeven = intern ("even");
7312 staticpro (&Qeven);
7313 QCflowcontrol = intern (":flowcontrol");
7314 staticpro (&QCflowcontrol);
7315 Qhw = intern ("hw");
7316 staticpro (&Qhw);
7317 Qsw = intern ("sw");
7318 staticpro (&Qsw);
7319 QCsummary = intern (":summary");
7320 staticpro (&QCsummary);
7321
7322 Qreal = intern ("real");
7323 staticpro (&Qreal);
7324 Qnetwork = intern ("network");
7325 staticpro (&Qnetwork);
7326 Qserial = intern ("serial");
7327 staticpro (&Qserial);
7328
7329 QCname = intern (":name");
7330 staticpro (&QCname);
7331 QCbuffer = intern (":buffer");
7332 staticpro (&QCbuffer);
7333 QChost = intern (":host");
7334 staticpro (&QChost);
7335 QCservice = intern (":service");
7336 staticpro (&QCservice);
7337 QCtype = intern (":type");
7338 staticpro (&QCtype);
7339 QClocal = intern (":local");
7340 staticpro (&QClocal);
7341 QCremote = intern (":remote");
7342 staticpro (&QCremote);
7343 QCcoding = intern (":coding");
7344 staticpro (&QCcoding);
7345 QCserver = intern (":server");
7346 staticpro (&QCserver);
7347 QCnowait = intern (":nowait");
7348 staticpro (&QCnowait);
7349 QCsentinel = intern (":sentinel");
7350 staticpro (&QCsentinel);
7351 QClog = intern (":log");
7352 staticpro (&QClog);
7353 QCnoquery = intern (":noquery");
7354 staticpro (&QCnoquery);
7355 QCstop = intern (":stop");
7356 staticpro (&QCstop);
7357 QCoptions = intern (":options");
7358 staticpro (&QCoptions);
7359 QCplist = intern (":plist");
7360 staticpro (&QCplist);
7361
7362 Qlast_nonmenu_event = intern ("last-nonmenu-event");
7363 staticpro (&Qlast_nonmenu_event);
7364
7365 staticpro (&Vprocess_alist);
7366 #ifdef SIGCHLD
7367 staticpro (&deleted_pid_list);
7368 #endif
7369
7370 Qeuid = intern ("euid");
7371 staticpro (&Qeuid);
7372 Qegid = intern ("egid");
7373 staticpro (&Qegid);
7374 Quser = intern ("user");
7375 staticpro (&Quser);
7376 Qgroup = intern ("group");
7377 staticpro (&Qgroup);
7378 Qcomm = intern ("comm");
7379 staticpro (&Qcomm);
7380 Qstate = intern ("state");
7381 staticpro (&Qstate);
7382 Qppid = intern ("ppid");
7383 staticpro (&Qppid);
7384 Qpgrp = intern ("pgrp");
7385 staticpro (&Qpgrp);
7386 Qsess = intern ("sess");
7387 staticpro (&Qsess);
7388 Qttname = intern ("ttname");
7389 staticpro (&Qttname);
7390 Qtpgid = intern ("tpgid");
7391 staticpro (&Qtpgid);
7392 Qminflt = intern ("minflt");
7393 staticpro (&Qminflt);
7394 Qmajflt = intern ("majflt");
7395 staticpro (&Qmajflt);
7396 Qcminflt = intern ("cminflt");
7397 staticpro (&Qcminflt);
7398 Qcmajflt = intern ("cmajflt");
7399 staticpro (&Qcmajflt);
7400 Qutime = intern ("utime");
7401 staticpro (&Qutime);
7402 Qstime = intern ("stime");
7403 staticpro (&Qstime);
7404 Qtime = intern ("time");
7405 staticpro (&Qtime);
7406 Qcutime = intern ("cutime");
7407 staticpro (&Qcutime);
7408 Qcstime = intern ("cstime");
7409 staticpro (&Qcstime);
7410 Qctime = intern ("ctime");
7411 staticpro (&Qctime);
7412 Qpri = intern ("pri");
7413 staticpro (&Qpri);
7414 Qnice = intern ("nice");
7415 staticpro (&Qnice);
7416 Qthcount = intern ("thcount");
7417 staticpro (&Qthcount);
7418 Qstart = intern ("start");
7419 staticpro (&Qstart);
7420 Qvsize = intern ("vsize");
7421 staticpro (&Qvsize);
7422 Qrss = intern ("rss");
7423 staticpro (&Qrss);
7424 Qetime = intern ("etime");
7425 staticpro (&Qetime);
7426 Qpcpu = intern ("pcpu");
7427 staticpro (&Qpcpu);
7428 Qpmem = intern ("pmem");
7429 staticpro (&Qpmem);
7430 Qargs = intern ("args");
7431 staticpro (&Qargs);
7432
7433 DEFVAR_BOOL ("delete-exited-processes", &delete_exited_processes,
7434 doc: /* *Non-nil means delete processes immediately when they exit.
7435 A value of nil means don't delete them until `list-processes' is run. */);
7436
7437 delete_exited_processes = 1;
7438
7439 DEFVAR_LISP ("process-connection-type", &Vprocess_connection_type,
7440 doc: /* Control type of device used to communicate with subprocesses.
7441 Values are nil to use a pipe, or t or `pty' to use a pty.
7442 The value has no effect if the system has no ptys or if all ptys are busy:
7443 then a pipe is used in any case.
7444 The value takes effect when `start-process' is called. */);
7445 Vprocess_connection_type = Qt;
7446
7447 #ifdef ADAPTIVE_READ_BUFFERING
7448 DEFVAR_LISP ("process-adaptive-read-buffering", &Vprocess_adaptive_read_buffering,
7449 doc: /* If non-nil, improve receive buffering by delaying after short reads.
7450 On some systems, when Emacs reads the output from a subprocess, the output data
7451 is read in very small blocks, potentially resulting in very poor performance.
7452 This behavior can be remedied to some extent by setting this variable to a
7453 non-nil value, as it will automatically delay reading from such processes, to
7454 allow them to produce more output before Emacs tries to read it.
7455 If the value is t, the delay is reset after each write to the process; any other
7456 non-nil value means that the delay is not reset on write.
7457 The variable takes effect when `start-process' is called. */);
7458 Vprocess_adaptive_read_buffering = Qt;
7459 #endif
7460
7461 defsubr (&Sprocessp);
7462 defsubr (&Sget_process);
7463 defsubr (&Sget_buffer_process);
7464 defsubr (&Sdelete_process);
7465 defsubr (&Sprocess_status);
7466 defsubr (&Sprocess_exit_status);
7467 defsubr (&Sprocess_id);
7468 defsubr (&Sprocess_name);
7469 defsubr (&Sprocess_tty_name);
7470 defsubr (&Sprocess_command);
7471 defsubr (&Sset_process_buffer);
7472 defsubr (&Sprocess_buffer);
7473 defsubr (&Sprocess_mark);
7474 defsubr (&Sset_process_filter);
7475 defsubr (&Sprocess_filter);
7476 defsubr (&Sset_process_sentinel);
7477 defsubr (&Sprocess_sentinel);
7478 defsubr (&Sset_process_window_size);
7479 defsubr (&Sset_process_inherit_coding_system_flag);
7480 defsubr (&Sprocess_inherit_coding_system_flag);
7481 defsubr (&Sset_process_query_on_exit_flag);
7482 defsubr (&Sprocess_query_on_exit_flag);
7483 defsubr (&Sprocess_contact);
7484 defsubr (&Sprocess_plist);
7485 defsubr (&Sset_process_plist);
7486 defsubr (&Slist_processes);
7487 defsubr (&Sprocess_list);
7488 defsubr (&Sstart_process);
7489 #ifdef HAVE_SERIAL
7490 defsubr (&Sserial_process_configure);
7491 defsubr (&Smake_serial_process);
7492 #endif /* HAVE_SERIAL */
7493 #ifdef HAVE_SOCKETS
7494 defsubr (&Sset_network_process_option);
7495 defsubr (&Smake_network_process);
7496 defsubr (&Sformat_network_address);
7497 #endif /* HAVE_SOCKETS */
7498 #if defined(HAVE_SOCKETS) && defined(HAVE_NET_IF_H) && defined(HAVE_SYS_IOCTL_H)
7499 #ifdef SIOCGIFCONF
7500 defsubr (&Snetwork_interface_list);
7501 #endif
7502 #if defined(SIOCGIFADDR) || defined(SIOCGIFHWADDR) || defined(SIOCGIFFLAGS)
7503 defsubr (&Snetwork_interface_info);
7504 #endif
7505 #endif /* HAVE_SOCKETS ... */
7506 #ifdef DATAGRAM_SOCKETS
7507 defsubr (&Sprocess_datagram_address);
7508 defsubr (&Sset_process_datagram_address);
7509 #endif
7510 defsubr (&Saccept_process_output);
7511 defsubr (&Sprocess_send_region);
7512 defsubr (&Sprocess_send_string);
7513 defsubr (&Sinterrupt_process);
7514 defsubr (&Skill_process);
7515 defsubr (&Squit_process);
7516 defsubr (&Sstop_process);
7517 defsubr (&Scontinue_process);
7518 defsubr (&Sprocess_running_child_p);
7519 defsubr (&Sprocess_send_eof);
7520 defsubr (&Ssignal_process);
7521 defsubr (&Swaiting_for_user_input_p);
7522 defsubr (&Sprocess_type);
7523 defsubr (&Sset_process_coding_system);
7524 defsubr (&Sprocess_coding_system);
7525 defsubr (&Sset_process_filter_multibyte);
7526 defsubr (&Sprocess_filter_multibyte_p);
7527 defsubr (&Slist_system_processes);
7528 defsubr (&Sprocess_attributes);
7529 }
7530
7531 \f
7532 #else /* not subprocesses */
7533
7534 #include <sys/types.h>
7535 #include <errno.h>
7536 #include <sys/stat.h>
7537 #include <stdlib.h>
7538 #include <fcntl.h>
7539 #ifdef HAVE_UNISTD_H
7540 #include <unistd.h>
7541 #endif
7542
7543 #include "lisp.h"
7544 #include "systime.h"
7545 #include "character.h"
7546 #include "coding.h"
7547 #include "termopts.h"
7548 #include "sysselect.h"
7549
7550 extern int frame_garbaged;
7551
7552 extern EMACS_TIME timer_check ();
7553 extern int timers_run;
7554
7555 Lisp_Object QCtype, QCname;
7556
7557 Lisp_Object Qeuid, Qegid, Qcomm, Qstate, Qppid, Qpgrp, Qsess, Qttname, Qtpgid;
7558 Lisp_Object Qminflt, Qmajflt, Qcminflt, Qcmajflt, Qutime, Qstime, Qcstime;
7559 Lisp_Object Qcutime, Qpri, Qnice, Qthcount, Qstart, Qvsize, Qrss, Qargs;
7560 Lisp_Object Quser, Qgroup, Qetime, Qpcpu, Qpmem, Qtime, Qctime;
7561
7562 /* As described above, except assuming that there are no subprocesses:
7563
7564 Wait for timeout to elapse and/or keyboard input to be available.
7565
7566 time_limit is:
7567 timeout in seconds, or
7568 zero for no limit, or
7569 -1 means gobble data immediately available but don't wait for any.
7570
7571 read_kbd is a Lisp_Object:
7572 0 to ignore keyboard input, or
7573 1 to return when input is available, or
7574 -1 means caller will actually read the input, so don't throw to
7575 the quit handler.
7576
7577 see full version for other parameters. We know that wait_proc will
7578 always be NULL, since `subprocesses' isn't defined.
7579
7580 do_display != 0 means redisplay should be done to show subprocess
7581 output that arrives.
7582
7583 Return true if we received input from any process. */
7584
7585 int
7586 wait_reading_process_output (time_limit, microsecs, read_kbd, do_display,
7587 wait_for_cell, wait_proc, just_wait_proc)
7588 int time_limit, microsecs, read_kbd, do_display;
7589 Lisp_Object wait_for_cell;
7590 struct Lisp_Process *wait_proc;
7591 int just_wait_proc;
7592 {
7593 register int nfds;
7594 EMACS_TIME end_time, timeout;
7595 SELECT_TYPE waitchannels;
7596 int xerrno;
7597
7598 /* What does time_limit really mean? */
7599 if (time_limit || microsecs)
7600 {
7601 EMACS_GET_TIME (end_time);
7602 EMACS_SET_SECS_USECS (timeout, time_limit, microsecs);
7603 EMACS_ADD_TIME (end_time, end_time, timeout);
7604 }
7605
7606 /* Turn off periodic alarms (in case they are in use)
7607 and then turn off any other atimers,
7608 because the select emulator uses alarms. */
7609 stop_polling ();
7610 turn_on_atimers (0);
7611
7612 while (1)
7613 {
7614 int timeout_reduced_for_timers = 0;
7615
7616 /* If calling from keyboard input, do not quit
7617 since we want to return C-g as an input character.
7618 Otherwise, do pending quit if requested. */
7619 if (read_kbd >= 0)
7620 QUIT;
7621
7622 /* Exit now if the cell we're waiting for became non-nil. */
7623 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7624 break;
7625
7626 /* Compute time from now till when time limit is up */
7627 /* Exit if already run out */
7628 if (time_limit == -1)
7629 {
7630 /* -1 specified for timeout means
7631 gobble output available now
7632 but don't wait at all. */
7633
7634 EMACS_SET_SECS_USECS (timeout, 0, 0);
7635 }
7636 else if (time_limit || microsecs)
7637 {
7638 EMACS_GET_TIME (timeout);
7639 EMACS_SUB_TIME (timeout, end_time, timeout);
7640 if (EMACS_TIME_NEG_P (timeout))
7641 break;
7642 }
7643 else
7644 {
7645 EMACS_SET_SECS_USECS (timeout, 100000, 0);
7646 }
7647
7648 /* If our caller will not immediately handle keyboard events,
7649 run timer events directly.
7650 (Callers that will immediately read keyboard events
7651 call timer_delay on their own.) */
7652 if (NILP (wait_for_cell))
7653 {
7654 EMACS_TIME timer_delay;
7655
7656 do
7657 {
7658 int old_timers_run = timers_run;
7659 timer_delay = timer_check (1);
7660 if (timers_run != old_timers_run && do_display)
7661 /* We must retry, since a timer may have requeued itself
7662 and that could alter the time delay. */
7663 redisplay_preserve_echo_area (14);
7664 else
7665 break;
7666 }
7667 while (!detect_input_pending ());
7668
7669 /* If there is unread keyboard input, also return. */
7670 if (read_kbd != 0
7671 && requeued_events_pending_p ())
7672 break;
7673
7674 if (! EMACS_TIME_NEG_P (timer_delay) && time_limit != -1)
7675 {
7676 EMACS_TIME difference;
7677 EMACS_SUB_TIME (difference, timer_delay, timeout);
7678 if (EMACS_TIME_NEG_P (difference))
7679 {
7680 timeout = timer_delay;
7681 timeout_reduced_for_timers = 1;
7682 }
7683 }
7684 }
7685
7686 /* Cause C-g and alarm signals to take immediate action,
7687 and cause input available signals to zero out timeout. */
7688 if (read_kbd < 0)
7689 set_waiting_for_input (&timeout);
7690
7691 /* Wait till there is something to do. */
7692
7693 if (! read_kbd && NILP (wait_for_cell))
7694 FD_ZERO (&waitchannels);
7695 else
7696 FD_SET (0, &waitchannels);
7697
7698 /* If a frame has been newly mapped and needs updating,
7699 reprocess its display stuff. */
7700 if (frame_garbaged && do_display)
7701 {
7702 clear_waiting_for_input ();
7703 redisplay_preserve_echo_area (15);
7704 if (read_kbd < 0)
7705 set_waiting_for_input (&timeout);
7706 }
7707
7708 if (read_kbd && detect_input_pending ())
7709 {
7710 nfds = 0;
7711 FD_ZERO (&waitchannels);
7712 }
7713 else
7714 nfds = select (1, &waitchannels, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
7715 &timeout);
7716
7717 xerrno = errno;
7718
7719 /* Make C-g and alarm signals set flags again */
7720 clear_waiting_for_input ();
7721
7722 /* If we woke up due to SIGWINCH, actually change size now. */
7723 do_pending_window_change (0);
7724
7725 if (time_limit && nfds == 0 && ! timeout_reduced_for_timers)
7726 /* We waited the full specified time, so return now. */
7727 break;
7728
7729 if (nfds == -1)
7730 {
7731 /* If the system call was interrupted, then go around the
7732 loop again. */
7733 if (xerrno == EINTR)
7734 FD_ZERO (&waitchannels);
7735 else
7736 error ("select error: %s", emacs_strerror (xerrno));
7737 }
7738 #ifdef SOLARIS2
7739 else if (nfds > 0 && (waitchannels & 1) && interrupt_input)
7740 /* System sometimes fails to deliver SIGIO. */
7741 kill (getpid (), SIGIO);
7742 #endif
7743 #ifdef SIGIO
7744 if (read_kbd && interrupt_input && (waitchannels & 1))
7745 kill (getpid (), SIGIO);
7746 #endif
7747
7748 /* Check for keyboard input */
7749
7750 if (read_kbd
7751 && detect_input_pending_run_timers (do_display))
7752 {
7753 swallow_events (do_display);
7754 if (detect_input_pending_run_timers (do_display))
7755 break;
7756 }
7757
7758 /* If there is unread keyboard input, also return. */
7759 if (read_kbd
7760 && requeued_events_pending_p ())
7761 break;
7762
7763 /* If wait_for_cell. check for keyboard input
7764 but don't run any timers.
7765 ??? (It seems wrong to me to check for keyboard
7766 input at all when wait_for_cell, but the code
7767 has been this way since July 1994.
7768 Try changing this after version 19.31.) */
7769 if (! NILP (wait_for_cell)
7770 && detect_input_pending ())
7771 {
7772 swallow_events (do_display);
7773 if (detect_input_pending ())
7774 break;
7775 }
7776
7777 /* Exit now if the cell we're waiting for became non-nil. */
7778 if (! NILP (wait_for_cell) && ! NILP (XCAR (wait_for_cell)))
7779 break;
7780 }
7781
7782 start_polling ();
7783
7784 return 0;
7785 }
7786
7787
7788 /* Don't confuse make-docfile by having two doc strings for this function.
7789 make-docfile does not pay attention to #if, for good reason! */
7790 DEFUN ("get-buffer-process", Fget_buffer_process, Sget_buffer_process, 1, 1, 0,
7791 0)
7792 (name)
7793 register Lisp_Object name;
7794 {
7795 return Qnil;
7796 }
7797
7798 /* Don't confuse make-docfile by having two doc strings for this function.
7799 make-docfile does not pay attention to #if, for good reason! */
7800 DEFUN ("process-inherit-coding-system-flag",
7801 Fprocess_inherit_coding_system_flag, Sprocess_inherit_coding_system_flag,
7802 1, 1, 0,
7803 0)
7804 (process)
7805 register Lisp_Object process;
7806 {
7807 /* Ignore the argument and return the value of
7808 inherit-process-coding-system. */
7809 return inherit_process_coding_system ? Qt : Qnil;
7810 }
7811
7812 /* Kill all processes associated with `buffer'.
7813 If `buffer' is nil, kill all processes.
7814 Since we have no subprocesses, this does nothing. */
7815
7816 void
7817 kill_buffer_processes (buffer)
7818 Lisp_Object buffer;
7819 {
7820 }
7821
7822 DEFUN ("list-system-processes", Flist_system_processes, Slist_system_processes,
7823 0, 0, 0,
7824 doc: /* Return a list of numerical process IDs of all running processes.
7825 If this functionality is unsupported, return nil.
7826
7827 See `process-attributes' for getting attributes of a process given its ID. */)
7828 ()
7829 {
7830 return list_system_processes ();
7831 }
7832
7833 DEFUN ("process-attributes", Fprocess_attributes,
7834 Sprocess_attributes, 1, 1, 0,
7835 doc: /* Return attributes of the process given by its PID, a number.
7836
7837 Value is an alist where each element is a cons cell of the form
7838
7839 \(KEY . VALUE)
7840
7841 If this functionality is unsupported, the value is nil.
7842
7843 See `list-system-processes' for getting a list of all process IDs.
7844
7845 The KEYs of the attributes that this function may return are listed
7846 below, together with the type of the associated VALUE (in parentheses).
7847 Not all platforms support all of these attributes; unsupported
7848 attributes will not appear in the returned alist.
7849 Unless explicitly indicated otherwise, numbers can have either
7850 integer or floating point values.
7851
7852 euid -- Effective user User ID of the process (number)
7853 user -- User name corresponding to euid (string)
7854 egid -- Effective user Group ID of the process (number)
7855 group -- Group name corresponding to egid (string)
7856 comm -- Command name (executable name only) (string)
7857 state -- Process state code, such as "S", "R", or "T" (string)
7858 ppid -- Parent process ID (number)
7859 pgrp -- Process group ID (number)
7860 sess -- Session ID, i.e. process ID of session leader (number)
7861 ttname -- Controlling tty name (string)
7862 tpgid -- ID of foreground process group on the process's tty (number)
7863 minflt -- number of minor page faults (number)
7864 majflt -- number of major page faults (number)
7865 cminflt -- cumulative number of minor page faults (number)
7866 cmajflt -- cumulative number of major page faults (number)
7867 utime -- user time used by the process, in the (HIGH LOW USEC) format
7868 stime -- system time used by the process, in the (HIGH LOW USEC) format
7869 time -- sum of utime and stime, in the (HIGH LOW USEC) format
7870 cutime -- user time used by the process and its children, (HIGH LOW USEC)
7871 cstime -- system time used by the process and its children, (HIGH LOW USEC)
7872 ctime -- sum of cutime and cstime, in the (HIGH LOW USEC) format
7873 pri -- priority of the process (number)
7874 nice -- nice value of the process (number)
7875 thcount -- process thread count (number)
7876 start -- time the process started, in the (HIGH LOW USEC) format
7877 vsize -- virtual memory size of the process in KB's (number)
7878 rss -- resident set size of the process in KB's (number)
7879 etime -- elapsed time the process is running, in (HIGH LOW USEC) format
7880 pcpu -- percents of CPU time used by the process (floating-point number)
7881 pmem -- percents of total physical memory used by process's resident set
7882 (floating-point number)
7883 args -- command line which invoked the process (string). */)
7884 (pid)
7885
7886 Lisp_Object pid;
7887 {
7888 return system_process_attributes (pid);
7889 }
7890
7891 void
7892 init_process ()
7893 {
7894 }
7895
7896 void
7897 syms_of_process ()
7898 {
7899 QCtype = intern (":type");
7900 staticpro (&QCtype);
7901 QCname = intern (":name");
7902 staticpro (&QCname);
7903 QCtype = intern (":type");
7904 staticpro (&QCtype);
7905 QCname = intern (":name");
7906 staticpro (&QCname);
7907 Qeuid = intern ("euid");
7908 staticpro (&Qeuid);
7909 Qegid = intern ("egid");
7910 staticpro (&Qegid);
7911 Quser = intern ("user");
7912 staticpro (&Quser);
7913 Qgroup = intern ("group");
7914 staticpro (&Qgroup);
7915 Qcomm = intern ("comm");
7916 staticpro (&Qcomm);
7917 Qstate = intern ("state");
7918 staticpro (&Qstate);
7919 Qppid = intern ("ppid");
7920 staticpro (&Qppid);
7921 Qpgrp = intern ("pgrp");
7922 staticpro (&Qpgrp);
7923 Qsess = intern ("sess");
7924 staticpro (&Qsess);
7925 Qttname = intern ("ttname");
7926 staticpro (&Qttname);
7927 Qtpgid = intern ("tpgid");
7928 staticpro (&Qtpgid);
7929 Qminflt = intern ("minflt");
7930 staticpro (&Qminflt);
7931 Qmajflt = intern ("majflt");
7932 staticpro (&Qmajflt);
7933 Qcminflt = intern ("cminflt");
7934 staticpro (&Qcminflt);
7935 Qcmajflt = intern ("cmajflt");
7936 staticpro (&Qcmajflt);
7937 Qutime = intern ("utime");
7938 staticpro (&Qutime);
7939 Qstime = intern ("stime");
7940 staticpro (&Qstime);
7941 Qtime = intern ("time");
7942 staticpro (&Qtime);
7943 Qcutime = intern ("cutime");
7944 staticpro (&Qcutime);
7945 Qcstime = intern ("cstime");
7946 staticpro (&Qcstime);
7947 Qctime = intern ("ctime");
7948 staticpro (&Qctime);
7949 Qpri = intern ("pri");
7950 staticpro (&Qpri);
7951 Qnice = intern ("nice");
7952 staticpro (&Qnice);
7953 Qthcount = intern ("thcount");
7954 staticpro (&Qthcount);
7955 Qstart = intern ("start");
7956 staticpro (&Qstart);
7957 Qvsize = intern ("vsize");
7958 staticpro (&Qvsize);
7959 Qrss = intern ("rss");
7960 staticpro (&Qrss);
7961 Qetime = intern ("etime");
7962 staticpro (&Qetime);
7963 Qpcpu = intern ("pcpu");
7964 staticpro (&Qpcpu);
7965 Qpmem = intern ("pmem");
7966 staticpro (&Qpmem);
7967 Qargs = intern ("args");
7968 staticpro (&Qargs);
7969
7970 defsubr (&Sget_buffer_process);
7971 defsubr (&Sprocess_inherit_coding_system_flag);
7972 defsubr (&Slist_system_processes);
7973 defsubr (&Sprocess_attributes);
7974 }
7975
7976 \f
7977 #endif /* not subprocesses */
7978
7979 /* arch-tag: 3706c011-7b9a-4117-bd4f-59e7f701a4c4
7980 (do not change this comment) */